题目链接
https://leetcode.com/problems/spiral-matrix-ii/
解题思路
代码
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
vector<vector<int>> ans(n, vector<int>(n, 0));
int count = 1;
int up = 0, down = n - 1, left = 0, right = n - 1;
while (up <= down && left <= right) {
if (up < n) {
for (int i = left; i <= right; ++i) {
ans[up][i] = count++;
}
up++;
}
if (right >= 0) {
for (int i = up; i <= down; ++i) {
ans[i][right] = count++;
}
right--;
}
if (down >= up) {
for (int i = right; i >= left; --i) {
ans[down][i] = count++;
}
down--;
}
if (left <= right) {
for (int i = down; i >= up; --i) {
ans[i][left] = count++;
}
left++;
}
}
return ans;
}
};
网友评论