File tree Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * @param {number[][] } grid
3
+ * @return {number }
4
+ */
5
+ var maxDistance = function ( grid ) {
6
+ const queue = [ ] ;
7
+ for ( let i = 0 ; i < grid . length ; i ++ ) {
8
+ for ( let j = 0 ; j < grid [ i ] . length ; j ++ ) {
9
+ if ( grid [ i ] [ j ] === 1 ) {
10
+ queue . push ( [ i , j , 0 ] ) ;
11
+ }
12
+ }
13
+ }
14
+ if ( queue . length === 0 || queue . length === grid . length * grid [ 0 ] . length ) {
15
+ return - 1 ;
16
+ }
17
+
18
+ let result = 0 ;
19
+ while ( queue . length ) {
20
+ const [ x , y , z ] = queue . shift ( ) ;
21
+ result = Math . max ( result , z ) ;
22
+ if ( grid [ x - 1 ] && grid [ x - 1 ] [ y ] === 0 ) {
23
+ grid [ x - 1 ] [ y ] = 1 ;
24
+ queue . push ( [ x - 1 , y , z + 1 ] ) ;
25
+ }
26
+ if ( grid [ x + 1 ] && grid [ x + 1 ] [ y ] === 0 ) {
27
+ grid [ x + 1 ] [ y ] = 1 ;
28
+ queue . push ( [ x + 1 , y , z + 1 ] ) ;
29
+ }
30
+ if ( grid [ x ] [ y - 1 ] === 0 ) {
31
+ grid [ x ] [ y - 1 ] = 1 ;
32
+ queue . push ( [ x , y - 1 , z + 1 ] ) ;
33
+ }
34
+ if ( grid [ x ] [ y + 1 ] === 0 ) {
35
+ grid [ x ] [ y + 1 ] = 1 ;
36
+ queue . push ( [ x , y + 1 , z + 1 ] ) ;
37
+ }
38
+ }
39
+ return result ;
40
+ } ;
You can’t perform that action at this time.
0 commit comments