Skip to content

Commit b9fe4e6

Browse files
authored
Create 2326-spiral-matrix-iv.js
1 parent f831fdf commit b9fe4e6

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

2326-spiral-matrix-iv.js

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* function ListNode(val, next) {
4+
* this.val = (val===undefined ? 0 : val)
5+
* this.next = (next===undefined ? null : next)
6+
* }
7+
*/
8+
/**
9+
* @param {number} m
10+
* @param {number} n
11+
* @param {ListNode} head
12+
* @return {number[][]}
13+
*/
14+
const spiralMatrix = function (m, n, head) {
15+
const mat = Array.from({ length: m }, () => Array(n).fill(-1));
16+
let cur = head;
17+
const dirs = [
18+
[0, 1],
19+
[1, 0],
20+
[0, -1],
21+
[-1, 0],
22+
];
23+
let i = 0,
24+
j = 0,
25+
left = 0,
26+
right = n - 1,
27+
top = 0,
28+
bottom = m - 1,
29+
idx = 0;
30+
while (cur) {
31+
mat[i][j] = cur.val;
32+
if (idx === 0 && j === right) {
33+
idx = (idx + 1) % 4;
34+
right--;
35+
} else if (idx === 1 && i === bottom) {
36+
idx = (idx + 1) % 4;
37+
bottom--;
38+
} else if (idx === 2 && j === left) {
39+
idx = (idx + 1) % 4;
40+
left++;
41+
} else if (idx === 3 && i === top + 1) {
42+
idx = (idx + 1) % 4;
43+
top++;
44+
}
45+
i += dirs[idx][0];
46+
j += dirs[idx][1];
47+
cur = cur.next;
48+
}
49+
50+
return mat;
51+
};

0 commit comments

Comments
 (0)