-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSpiralPrint
47 lines (47 loc) · 1.49 KB
/
SpiralPrint
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
class Solution {
public:
vector<int> spiralOrder(const vector<vector<int> > &matrix) {
int rows = matrix.size();
if (rows == 0) return vector<int> ();
int cols = matrix[0].size();
int row = 0, col = 0, layer = 0;
vector<int> res;
res.push_back(matrix[0][0]);
int dir = 1;
for (int step = 1; step < rows * cols; step++) {
switch(dir) { // based on dir, check and change dir, then move on
case 1: // supposed to go right
if (col == cols - layer - 1) { // reach right bound
row++;
dir = 2;
}
else col++;
break;
case 2: // supposed to go down
if (row == rows - layer - 1) { // reach downside bound
col--;
dir = 3;
}
else row++;
break;
case 3: // supposed to go left
if (col == layer) { // reach left bound
row--;
dir = 4;
}
else col--;
break;
case 4: // supposed to go up
if (row == layer + 1) { // reach upside bound
col++;
dir = 1;
layer++;
}
else row--;
break;
}
res.push_back(matrix[row][col]);
}
return res;
}
};