Skip to content

Commit ccb9524

Browse files
authored
Update 1091-shortest-path-in-binary-matrix.js
1 parent 94f9d11 commit ccb9524

File tree

1 file changed

+18
-18
lines changed

1 file changed

+18
-18
lines changed

1091-shortest-path-in-binary-matrix.js

Lines changed: 18 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -3,32 +3,32 @@
33
* @return {number}
44
*/
55
const shortestPathBinaryMatrix = function(grid) {
6-
let N = grid.length,
7-
qu = [[0, 0]],
8-
path = 1
6+
if(grid == null || grid.length === 0 || grid[0][0] === 1) return -1
7+
let res = 1
8+
const n = grid.length
99
const dirs = [
10-
[-1, 0],
1110
[1, 0],
12-
[0, -1],
11+
[-1, 0],
1312
[0, 1],
13+
[0, -1],
1414
[-1, -1],
1515
[-1, 1],
16+
[1, 1],
1617
[1, -1],
17-
[1, 1]
1818
]
19-
while (qu.length !== 0) {
20-
let cop = qu
21-
qu = []
22-
for (let [r, c] of cop) {
23-
if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length) continue
24-
if (grid[r][c] === 1) continue
25-
grid[r][c] = 1
26-
if (r === N - 1 && c === N - 1) return path
27-
for (let dir of dirs) {
28-
qu.push([r + dir[0], c + dir[1]])
19+
let q = [[0, 0]]
20+
while(q.length) {
21+
const tmp = q
22+
q = []
23+
for(let [x, y] of tmp) {
24+
if (x < 0 || x >= n || y < 0 || y >= n || grid[x][y] !== 0) continue
25+
if(x === n - 1 && y === n - 1) return res
26+
grid[x][y] = 1
27+
for(let [dx, dy] of dirs) {
28+
q.push([x + dx, y + dy])
2929
}
3030
}
31-
path++
31+
res++
3232
}
3333
return -1
34-
}
34+
};

0 commit comments

Comments
 (0)