Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit d8e1898

Browse files
committedJan 19, 2023
Add solution #59
1 parent 65b7eb9 commit d8e1898

File tree

2 files changed

+45
-0
lines changed

2 files changed

+45
-0
lines changed
 

‎README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,7 @@
5959
54|[Spiral Matrix](./0054-spiral-matrix.js)|Medium|
6060
57|[Insert Interval](./0057-insert-interval.js)|Medium|
6161
58|[Length of Last Word](./0058-length-of-last-word.js)|Easy|
62+
59|[Spiral Matrix II](./0059-spiral-matrix-ii.js)|Medium|
6263
62|[Unique Paths](./0062-unique-paths.js)|Medium|
6364
66|[Plus One](./0066-plus-one.js)|Easy|
6465
67|[Add Binary](./0067-add-binary.js)|Easy|

‎solutions/0059-spiral-matrix-ii.js

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
/**
2+
* 59. Spiral Matrix II
3+
* https://leetcode.com/problems/spiral-matrix-ii/
4+
* Difficulty: Medium
5+
*
6+
* Given a positive integer n, generate an n x n matrix filled with
7+
* elements from 1 to n2 in spiral order.
8+
*/
9+
10+
/**
11+
* @param {number} n
12+
* @return {number[][]}
13+
*/
14+
var generateMatrix = function(n) {
15+
const result = Array.from(new Array(n), () => new Array(n).fill(0));
16+
let top = 0;
17+
let right = n - 1;
18+
let bottom = n - 1;
19+
let left = 0;
20+
21+
for (let count = 0; count < (n * n);) {
22+
for (let i = left; i <= right; i++) {
23+
result[top][i] = ++count;
24+
}
25+
top++;
26+
27+
for (let i = top; i <= bottom; i++) {
28+
result[i][right] = ++count;
29+
}
30+
right--;
31+
32+
for (let i = right; top <= bottom && i >= left; i--) {
33+
result[bottom][i] = ++count;
34+
}
35+
bottom--;
36+
37+
for (let i = bottom; left <= right && i >= top; i--) {
38+
result[i][left] = ++count;
39+
}
40+
left++;
41+
}
42+
43+
return result;
44+
};

0 commit comments

Comments
 (0)
Please sign in to comment.