Spiral Matrix
Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
For example,
Given the following matrix:
1
2
3
4
5 [
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]You should return [1,2,3,6,9,8,7,4,5].
定义运动方向,使用状态来解决这个问题,注意坐标的计算即可。
AC代码: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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
vector<int> result;
int row = matrix.size();
int col = 0;
if (row != 0)
{
col = matrix[0].size();
}
if (col * row == 0)
{
return result;
}
int ri = 0;
int ci = 0;
bool left = false;
bool right = true;
bool up = false;
bool down = false;
int br = 0, er = row - 1;
int bc = 0, ec = col - 1;
while (result.size() != col * row)
{
result.push_back(matrix[ri][ci]);
if (!left && right && !up && !down)
{
if (ci == ec)
{
ci = ec;
right = false;
down = true;
br++;
ri++;
}
else
{
ci++;
}
}
else if (left && !right && !down && !up)
{
if (ci == bc)
{
ci = bc;
left = false;
up = true;
er--;
ri--;
}
else
{
ci--;
}
}
else if (!left && !right && down && !up)
{
if (ri >= er)
{
ri = er;
down = false;
left = true;
ec--;
ci--;
}
else
{
ri++;
}
}
else
{
if (ri <= br)
{
ri = br;
up = false;
right = true;
bc++;
ci++;
}
else
{
ri--;
}
}
}
return result;
}
};