-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathspiral_matrix.cpp
More file actions
52 lines (49 loc) · 1.43 KB
/
spiral_matrix.cpp
File metadata and controls
52 lines (49 loc) · 1.43 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
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
vector<int> result;
int total = matrix.size() * matrix[0].size();
int r = 0, c = 0;
int r_min = 0, r_max = matrix.size() - 1;
int c_min = 0, c_max = matrix[0].size() - 1;
enum direction { R, D, L, U } DIR = R;
while(result.size() < total){
result.push_back(matrix[r][c]);
switch(DIR){
case R:
if(c == c_max){
DIR = D;
r++;
r_min++;
}else
c++;
break;
case D:
if(r == r_max){
DIR = L;
c--;
c_max--;
}else
r++;
break;
case L:
if(c == c_min){
DIR = U;
r--;
r_max--;
}else
c--;
break;
case U:
if(r == r_min){
DIR = R;
c_min++;
c++;
}else
r--;
break;
}
}
return result;
}
};