forked from AnasImloul/Leetcode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSpiral Matrix IV.js
53 lines (52 loc) · 1.6 KB
/
Spiral Matrix IV.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
// Runtime: 1122 ms (Top 6.48%) | Memory: 103.4 MB (Top 52.52%)
var spiralMatrix = function(m, n, head) {
var matrix = new Array(m).fill().map(()=> new Array(n).fill(-1))
var row=0, col=0;
var direction="right";
while(head)
{
matrix[row][col]=head.val;
if(direction=="right")
{
if(col+1 == n || matrix[row][col+1] != -1)
{
direction="down"
row++;
}
else
col++
}
else if(direction=="down")
{
if(row+1 == m || matrix[row+1][col] != -1)
{
direction="left"
col--;
}
else
row++
}
else if(direction=="left")
{
if(col == 0 || matrix[row][col-1] != -1)
{
direction="up"
row--;
}
else
col--
}
else if(direction=="up")
{
if(row == 0 || matrix[row-1][col] != -1)
{
direction="right"
col++;
}
else
row--
}
head = head.next;
}
return matrix;
};