59. Spiral Matrix II
Last updated
Last updated
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
vector<vector<int>> res(n, vector<int>(n, 0));
if (n == 0) {
return res;
}
int top = 0, bottom = n, left = 0, right = n, cnt = 0, total = n * n;
while (top <= bottom - 1 && left <= right - 1) {
for (int i = left; i < right; i++) {
if (cnt < total) {
res[top][i] = cnt + 1;
cnt++;
}
}
++top;
for (int i = top; i < bottom; i++) {
if (cnt < total) {
res[i][right - 1] = cnt + 1;
cnt++;
}
}
--right;
for (int i = right - 1; i >= left; i--) {
if (cnt < total) {
res[bottom - 1][i] = cnt + 1;
cnt++;
}
}
--bottom;
for (int i = bottom - 1; i >= top; i--) {
if (cnt < total) {
res[i][left] = cnt + 1;
cnt++;
}
}
++left;
}
return res;
}
};