File tree Expand file tree Collapse file tree 1 file changed +18
-18
lines changed Expand file tree Collapse file tree 1 file changed +18
-18
lines changed Original file line number Diff line number Diff line change 3
3
* @return {number }
4
4
*/
5
5
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
9
9
const dirs = [
10
- [ - 1 , 0 ] ,
11
10
[ 1 , 0 ] ,
12
- [ 0 , - 1 ] ,
11
+ [ - 1 , 0 ] ,
13
12
[ 0 , 1 ] ,
13
+ [ 0 , - 1 ] ,
14
14
[ - 1 , - 1 ] ,
15
15
[ - 1 , 1 ] ,
16
+ [ 1 , 1 ] ,
16
17
[ 1 , - 1 ] ,
17
- [ 1 , 1 ]
18
18
]
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 ] )
29
29
}
30
30
}
31
- path ++
31
+ res ++
32
32
}
33
33
return - 1
34
- }
34
+ } ;
You can’t perform that action at this time.
0 commit comments