Skip to content

Commit 11f1b4e

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

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

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

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,3 +32,49 @@ const shortestPathBinaryMatrix = function(grid) {
3232
}
3333
return -1
3434
};
35+
36+
// another
37+
38+
/**
39+
* @param {number[][]} grid
40+
* @return {number}
41+
*/
42+
const shortestPathBinaryMatrix = function(grid) {
43+
if(grid == null || grid.length === 0 || grid[0][0] === 1) return -1
44+
let res = 1
45+
const n = grid.length
46+
const dirs = [
47+
[1, 0],
48+
[-1, 0],
49+
[0, 1],
50+
[0, -1],
51+
[-1, -1],
52+
[-1, 1],
53+
[1, 1],
54+
[1, -1],
55+
]
56+
let q = [[0, 0]]
57+
while(q.length) {
58+
let ref = q
59+
q = []
60+
for(let [x, y] of ref) {
61+
if(x === n - 1 && y === n - 1) return res
62+
grid[x][y] = 1
63+
for(let [dx, dy] of dirs) {
64+
const nx = x + dx, ny = y + dy
65+
if(helper(grid, nx, ny)) {
66+
q.push([nx, ny])
67+
grid[nx][ny] = 1 // very important
68+
}
69+
}
70+
}
71+
res++
72+
}
73+
return -1
74+
};
75+
76+
function helper(grid, i, j) {
77+
const n = grid.length
78+
if(i < 0 || i >= n || j < 0 || j >= n || grid[i][j] !== 0) return false
79+
return true
80+
}

0 commit comments

Comments
 (0)