forked from everthis/leetcode-js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1091-shortest-path-in-binary-matrix.js
80 lines (77 loc) · 1.55 KB
/
1091-shortest-path-in-binary-matrix.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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
/**
* @param {number[][]} grid
* @return {number}
*/
const shortestPathBinaryMatrix = function(grid) {
if(grid == null || grid.length === 0 || grid[0][0] === 1) return -1
let res = 1
const n = grid.length
const dirs = [
[1, 0],
[-1, 0],
[0, 1],
[0, -1],
[-1, -1],
[-1, 1],
[1, 1],
[1, -1],
]
let q = [[0, 0]]
while(q.length) {
const tmp = q
q = []
for(let [x, y] of tmp) {
if (x < 0 || x >= n || y < 0 || y >= n || grid[x][y] !== 0) continue
if(x === n - 1 && y === n - 1) return res
grid[x][y] = 1
for(let [dx, dy] of dirs) {
q.push([x + dx, y + dy])
}
}
res++
}
return -1
};
// another
/**
* @param {number[][]} grid
* @return {number}
*/
const shortestPathBinaryMatrix = function(grid) {
if(grid == null || grid.length === 0 || grid[0][0] === 1) return -1
let res = 1
const n = grid.length
const dirs = [
[1, 0],
[-1, 0],
[0, 1],
[0, -1],
[-1, -1],
[-1, 1],
[1, 1],
[1, -1],
]
let q = [[0, 0]]
while(q.length) {
let ref = q
q = []
for(let [x, y] of ref) {
if(x === n - 1 && y === n - 1) return res
grid[x][y] = 1
for(let [dx, dy] of dirs) {
const nx = x + dx, ny = y + dy
if(helper(grid, nx, ny)) {
q.push([nx, ny])
grid[nx][ny] = 1 // very important
}
}
}
res++
}
return -1
};
function helper(grid, i, j) {
const n = grid.length
if(i < 0 || i >= n || j < 0 || j >= n || grid[i][j] !== 0) return false
return true
}