@@ -281,3 +281,86 @@ const minPushBox = function (grid) {
281
281
}
282
282
}
283
283
284
+ // another
285
+
286
+ /**
287
+ * @param {character[][] } grid
288
+ * @return {number }
289
+ */
290
+ const minPushBox = function ( grid ) {
291
+ const m = grid . length ,
292
+ n = grid [ 0 ] . length
293
+ let target , person , box
294
+ for ( let i = 0 ; i < m ; i ++ ) {
295
+ for ( let j = 0 ; j < n ; j ++ ) {
296
+ if ( grid [ i ] [ j ] === 'T' ) target = [ i , j ]
297
+ else if ( grid [ i ] [ j ] === 'B' ) box = [ i , j ]
298
+ else if ( grid [ i ] [ j ] === 'S' ) person = [ i , j ]
299
+ }
300
+ }
301
+
302
+ const valid = ( [ x , y ] ) => {
303
+ return x >= 0 && x < m && y >= 0 && y < n && grid [ x ] [ y ] !== '#'
304
+ }
305
+
306
+ const check = ( cur , dest , box ) => {
307
+ const q = [ cur ]
308
+ const visited = new Set ( [ `${ box [ 0 ] } ,${ box [ 1 ] } ` ] )
309
+ const dirs = [
310
+ [ - 1 , 0 ] ,
311
+ [ 1 , 0 ] ,
312
+ [ 0 , 1 ] ,
313
+ [ 0 , - 1 ] ,
314
+ ]
315
+
316
+ while ( q . length ) {
317
+ const pos = q . shift ( )
318
+ if ( pos . join ( ',' ) === dest . join ( ',' ) ) return true
319
+ const newPos = [ ]
320
+ for ( const [ dx , dy ] of dirs ) newPos . push ( [ pos [ 0 ] + dx , pos [ 1 ] + dy ] )
321
+ for ( const [ nx , ny ] of newPos ) {
322
+ const k = `${ nx } ,${ ny } `
323
+ if ( valid ( [ nx , ny ] ) && ! visited . has ( k ) ) {
324
+ visited . add ( k )
325
+ q . push ( [ nx , ny ] )
326
+ }
327
+ }
328
+ }
329
+
330
+ return false
331
+ }
332
+
333
+ const q = [ [ 0 , box , person ] ]
334
+ const vis = new Set ( [ `${ box . join ( ',' ) } ,${ person . join ( ',' ) } ` ] )
335
+ while ( q . length ) {
336
+ const [ dist , box , person ] = q . shift ( )
337
+ if ( box . join ( ',' ) === target . join ( ',' ) ) return dist
338
+
339
+ const bCoord = [
340
+ [ box [ 0 ] + 1 , box [ 1 ] ] ,
341
+ [ box [ 0 ] - 1 , box [ 1 ] ] ,
342
+ [ box [ 0 ] , box [ 1 ] + 1 ] ,
343
+ [ box [ 0 ] , box [ 1 ] - 1 ] ,
344
+ ]
345
+ const pCoord = [
346
+ [ box [ 0 ] - 1 , box [ 1 ] ] ,
347
+ [ box [ 0 ] + 1 , box [ 1 ] ] ,
348
+ [ box [ 0 ] , box [ 1 ] - 1 ] ,
349
+ [ box [ 0 ] , box [ 1 ] + 1 ] ,
350
+ ]
351
+
352
+ for ( let i = 0 ; i < 4 ; i ++ ) {
353
+ const [ newBox , newPerson ] = [ bCoord [ i ] , pCoord [ i ] ]
354
+ const key = `${ newBox . join ( ',' ) } ,${ box . join ( ',' ) } `
355
+ if ( valid ( newBox ) && ! vis . has ( key ) ) {
356
+ if ( valid ( newPerson ) && check ( person , newPerson , box ) ) {
357
+ vis . add ( key )
358
+ q . push ( [ dist + 1 , newBox , box ] )
359
+ }
360
+ }
361
+ }
362
+ }
363
+
364
+ return - 1
365
+ }
366
+
0 commit comments