[LeetCode] Spiral Matrix II

59. Spiral Matrix II

Given a positive integer n, generate an n x n matrix filled with elements from 1 to n2 in spiral order.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
vector<vector<int>> res(n, vector<int>(n));
int y = 0, x = 0, dy[4]{-1,0,1,0}, dx[4]{0,1,0,-1}, d = 1;
for(int i = 1; i <= n * n; i++) {
res[y][x] = i;
int ny = y + dy[d], nx = x + dx[d];
if(0 <= ny and ny < n and 0 <= nx and nx < n and res[ny][nx] == 0) {
y = ny, x = nx;
} else {
d = (d + 1) % 4;
y += dy[d], x += dx[d];
}
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/04/03/PS/LeetCode/spiral-matrix-ii/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.