File tree Expand file tree Collapse file tree 1 file changed +46
-0
lines changed Expand file tree Collapse file tree 1 file changed +46
-0
lines changed Original file line number Diff line number Diff line change @@ -32,3 +32,49 @@ const shortestPathBinaryMatrix = function(grid) {
32
32
}
33
33
return - 1
34
34
} ;
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
+ }
You can’t perform that action at this time.
0 commit comments