-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0054-spiral-matrix.cpp
More file actions
76 lines (69 loc) · 1.74 KB
/
0054-spiral-matrix.cpp
File metadata and controls
76 lines (69 loc) · 1.74 KB
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
#include <vector>
using namespace std;
enum direction
{
RIGHT,
DOWN,
LEFT,
UP
};
class Solution
{
public:
vector<int> spiralOrder(vector<vector<int>> &matrix)
{
direction currDirection = RIGHT;
vector<int> ans;
int i = 0, j = 0, cnt = 0, m = matrix.size(), n = matrix[0].size();
while (cnt < m * n)
{
ans.push_back(matrix[i][j]);
matrix[i][j] = 101;
cnt++;
if (cnt < m * n)
{
switch (currDirection)
{
case RIGHT:
j++;
if (j>=n || matrix[i][j] == 101) {
currDirection = DOWN;
i++;
j--;
}
break;
case DOWN:
i++;
if (i>=m || matrix[i][j] == 101) {
currDirection = LEFT;
i--;
j--;
}
break;
case LEFT:
j--;
if (j<0 || matrix[i][j] == 101) {
currDirection = UP;
i--;
j++;
}
break;
case UP:
i--;
if (i<0 || matrix[i][j] == 101) {
currDirection = RIGHT;
i++;
j++;
}
break;
}
}
}
return ans;
}
};
int main() {
vector<vector<int>> q {{1,2,3},{8,9,4}, {7,6,5}};
Solution s;
s.spiralOrder(q);
}