-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathspiral_traversal.cpp
55 lines (43 loc) · 937 Bytes
/
spiral_traversal.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
//spiral traversal
#include <bits/stdc++.h>
using namespace std;
vector<int> spiralOrder(vector<vector<int> >& matrix)
{
int m = matrix.size(), n = matrix[0].size();
vector<int> ans;
if (m == 0)
return ans;
vector<vector<bool> > seen(m, vector<bool>(n, false));
int dr[] = { 0, 1, 0, -1 };
int dc[] = { 1, 0, -1, 0 };
int x = 0, y = 0, di = 0;
for (int i = 0; i < m * n; i++) {
ans.push_back(matrix[x][y]);
seen[x][y] = true;
int newX = x + dr[di];
int newY = y + dc[di];
if (0 <= newX && newX < m && 0 <= newY && newY < n
&& !seen[newX][newY]) {
x = newX;
y = newY;
}
else {
di = (di + 1) % 4;
x += dr[di];
y += dc[di];
}
}
return ans;
}
int main()
{
int n , m;cin>>n >>m;
vector<vector<int> > a(n , vector<int>(m , 0));
for(int i = 0 ;i<n;i++)
for(int j = 0 ; j<m ;j++)
cin>>a[i][j];
for (int x : spiralOrder(a)) {
cout << x << " ";
}
return 0;
}