地址:https://leetcode.com/problems/spiral-matrix/
题目:
Given a matrix of
m
x
n
m x n
mxn elements (
m
m
m rows,
n
n
n columns), return all elements of the matrix in spiral order.
Example 1:
Example 2:
理解:
按规则走一遍就可以了。
实现:
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
vector<int> res;
if(matrix.empty()) return res;
int u = 0, d = matrix.size()-1, l = 0, r = matrix[0].size()-1;
char direction = 'r';
res.push_back(matrix[0][0]);
int i = 0, j = 0;
while (l<=r&&u<=d) {
switch (direction) {
case 'r':
while (j < r) {
res.push_back(matrix[i][j+1]);
++j;
}
direction = 'd';
u++;
break;
case 'd':
while (i < d) {
res.push_back(matrix[i+1][j]);
++i;
}
direction = 'l';
r--;
break;
case 'l':
while (j > l) {
res.push_back(matrix[i][j-1]);
--j;
}
direction = 'u';
d--;
break;
case 'u':
while (i > u) {
res.push_back(matrix[i-1][j]);
--i;
}
direction = 'r';
++l;
}
}
return res;
}
};
虽然写出来了,但是感觉思维有点混乱。
重新写一下吧。
实现2:
可以理解每次走最外圈的矩形。
四个顶点分别是
(
x
1
,
y
1
)
(x_1,y_1)
(x1,y1),
(
x
1
,
y
2
)
(x_1,y_2)
(x1,y2),
(
x
2
,
y
1
)
(x_2,y_1)
(x2,y1)和
(
x
2
,
y
2
)
(x_2,y_2)
(x2,y2)。
注意到每次走完一条边,就把对应的坐标缩小了,因此需要多一次判断是否满足构成矩形的条件,不够就退出,说明已经遍历完了。这样的思路更清楚,而且避免了上面一直用ij
来索引导致奇怪的赋值下标。
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
if (matrix.empty()) return{};
int x1 = 0, y1 = 0;
int x2 = matrix.size() - 1, y2 = matrix[0].size() - 1;
vector<int> res((x2 + 1)*(y2 + 1));
int cnt = 0;
while (x1<=x2&&y1<=y2) {
for (int i = x1, j = y1; j <= y2; ++j) {
res[cnt++] = matrix[i][j];
}
++x1;
if (x1 > x2 || y1 > y2) break;
for (int i = x1, j = y2; i <= x2; ++i) {
res[cnt++] = matrix[i][j];
}
--y2;
if (x1 > x2 || y1 > y2) break;
for (int i = x2, j = y2; j >= y1; --j) {
res[cnt++] = matrix[i][j];
}
--x2;
if (x1 > x2 || y1 > y2) break;
for (int i = x2, j = y1; i >= x1; --i) {
res[cnt++] = matrix[i][j];
}
++y1;
}
return res;
}
};