LeetCode 59. Spiral Matrix II

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
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
vector<vector<int>> ans(n, vector<int>(n, 0));
int i = 1, x1 = 0, y1 = 0, x2 = n -1, y2 = n - 1;
while (n > 1) {
int x = x1, y = y1;
while (y < y2)
ans[x][y++] = i++;
while (x < x2)
ans[x++][y] = i++;
while (y > y1)
ans[x][y--] = i++;
while (x > x1)
ans[x--][y] = i++;
++x1;
++y1;
--x2;
--y2;
n -= 2;
}
if (n & 1)
ans[x1][y1] = i;
return ans;
}
};