54. 螺旋矩阵

Introduction

Question:54. 螺旋矩阵

Analysis

要实现回行遍历(注意不是螺旋)只需要用一个state来标识行动方向,然后通过判断是否到达边界来更新方向即可。

而螺旋遍历的话,还需要用而外的4个值来分别控制横向、纵向的边界。在每次切换边界时更新对应的边界。

Implement

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
int ifirst, ilast, jfirst, jlast;
vector<int> moveI{0, 1, 0, -1};
vector<int> moveJ{1, 0, -1, 0};
void transform(int &i, int &j, int &state) {
if (state == 0 && j == jlast) {
state = (state + 1) % 4;
jlast--;
} else if (state == 1 && i == ilast) {
state = (state + 1) % 4;
ilast--;
} else if (state == 2 && j == jfirst) {
state = (state + 1) % 4;
jfirst++;
} else if (state == 3 && i == ifirst) {
state = (state + 1) % 4;
ifirst++;
}
i += moveI[state];
j += moveJ[state];
}
vector<int> spiralOrder(vector<vector<int>>& matrix) {
int m = matrix.size();
if (m == 0) return vector<int>();
int n = matrix[0].size();
vector<int> res(m*n);
int i = 0, j = 0;
ifirst = jfirst = 0;
ilast = m - 1;
jlast = n - 1;
ifirst++;

int state = 0;

for(int index = 0, size = m*n; index < size; index++) {
res[index] = matrix[i][j];
transform(i, j, state);
}
return res;
}