题意
题解
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
int m = matrix.size(), n = matrix[0].size();
int cnt = m * n;
vector<int> ans;
int left = 0, right = n - 1, up = 0, down = m - 1;
while (cnt) {
for(int j = left; j <= right; j++) {
ans.push_back(matrix[up][j]);
cnt--;
if (cnt == 0) break;
}
if (cnt == 0) break;
up++;
for (int i = up; i <= down; i++) {
ans.push_back(matrix[i][right]);
cnt--;
if (cnt == 0) break;
}
if (cnt == 0) break;
right--;
for (int j = right; j >= left; j--) {
ans.push_back(matrix[down][j]);
cnt--;
if (cnt == 0) break;
}
if (cnt == 0) break;
down--;
for (int i = down; i >= up; i--) {
ans.push_back(matrix[i][left]);
cnt--;
if (cnt == 0) break;
}
if (cnt == 0) break;
left++;
}
return ans;
}
};
版权声明:本文为younothings原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。