Skip to content

Commit 09a2991

Browse files
Create 0059-spiral-matrix-ii.js
1 parent 0f47800 commit 09a2991

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

javascript/0059-spiral-matrix-ii.js

+38
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
/**
2+
* https://leetcode.com/problems/spiral-matrix-ii/
3+
* @param {number} n
4+
* @return {number[][]}
5+
*/
6+
var generateMatrix = function(n) {
7+
let matrix = Array.from(Array(n),() => Array(n));
8+
9+
let top = 0,bottom = n-1,left = 0,right = n-1;
10+
let element = 1;
11+
12+
while(top <= bottom && left <= right){
13+
14+
for(let i = left;i <= right; i++){
15+
matrix[top][i] = element++;
16+
}
17+
top++;
18+
19+
for(let i = top;i <= bottom; i++){
20+
matrix[i][right] = element++;
21+
}
22+
right--;
23+
24+
for(let i = right; i>= left; i--){
25+
matrix[bottom][i] = element++;
26+
}
27+
bottom--;
28+
29+
for(let i = bottom;i >= top; i--){
30+
matrix[i][left] = element++;
31+
}
32+
left++;
33+
}
34+
return matrix;
35+
};
36+
37+
// Runtime: 54 ms, 0.62% of solutions used 54 ms of runtime for spiral matrix ii.
38+
// Memory Usage: 41.9 MB, 7.07% of solutions used 41.9 MB of memory for spiral matrix ii.

0 commit comments

Comments
 (0)