Skip to content

Commit 03700b8

Browse files
committed
Create 59.螺旋矩阵 II.js
1 parent c5e0e20 commit 03700b8

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

59.螺旋矩阵 II.js

+27
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
/**
2+
* @param {number} n
3+
* @return {number[][]}
4+
*/
5+
var generateMatrix = function(n) {
6+
const directions = [[0, 1], [1, 0], [0, -1], [-1, 0]];
7+
let d = 0;
8+
let x = 0, y = -1;
9+
let current = 0;
10+
let result = new Array(n);
11+
for (let i = 0; i < n; i++) {
12+
result[i] = new Array(n).fill(0);
13+
}
14+
while (current < n * n) {
15+
const nextX = x + directions[d][0];
16+
const nextY = y + directions[d][1];
17+
if (result[nextX] && result[nextX][nextY] === 0) {
18+
current++;
19+
result[nextX][nextY] = current;
20+
x = nextX;
21+
y = nextY;
22+
} else {
23+
d = (d + 1) % directions.length;
24+
}
25+
}
26+
return result;
27+
};

0 commit comments

Comments
 (0)