forked from MainakRepositor/500-CPP
-
Notifications
You must be signed in to change notification settings - Fork 0
/
134.cpp
55 lines (46 loc) · 866 Bytes
/
134.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
#include <bits/stdc++.h>
using namespace std;
vector<int> spiralOrder(vector<vector<int>> &matrix)
{
vector<int> ans;
if (matrix.size() == 0)
return ans;
int R = matrix.size(), C = matrix[0].size();
bool seen[R][C];
int dr[] = { 0, 1, 0, -1 };
int dc[] = { 1, 0, -1, 0 };
int r = 0, c = 0, di = 0;
// Iterate from 0 to R * C - 1
for (int i = 0; i < R * C; i++) {
ans.push_back(matrix[r]);
seen[r] = true;
int cr = r + dr[di];
int cc = c + dc[di];
if (0 <= cr && cr < R && 0 <= cc && cc < C
&& !seen[cr][cc])
{
r = cr;
c = cc;
}
else
{
di = (di + 1) % 4;
r += dr[di];
c += dc[di];
}
}
return ans;
}
// Driver code
int main()
{
vector<vector<int>> a { { 1, 2, 3, 4 },
{ 5, 6, 7, 8 },
{ 9, 10, 11, 12 },
{ 13, 14, 15, 16 } };
for(int x:spiralOrder(a))
{
cout << x << " ";
}
return 0;
}