File tree Expand file tree Collapse file tree 1 file changed +35
-0
lines changed Expand file tree Collapse file tree 1 file changed +35
-0
lines changed Original file line number Diff line number Diff line change 1+ /**
2+ * @param {number[][] } grid
3+ * @return {number }
4+ */
5+ const minCost = function ( grid ) {
6+ const n = grid . length
7+ const m = grid [ 0 ] . length
8+ const moves = [
9+ [ 0 , 1 ] ,
10+ [ 0 , - 1 ] ,
11+ [ 1 , 0 ] ,
12+ [ - 1 , 0 ] ,
13+ ]
14+ const dp = [ ...new Array ( n ) ] . map ( ( e ) => [ ...new Array ( m ) ] . fill ( Infinity ) )
15+ dp [ 0 ] [ 0 ] = 0
16+ let queue = [ [ 0 , 0 ] ]
17+ while ( queue . length > 0 ) {
18+ const temp = [ ]
19+ for ( let i = 0 ; i < queue . length ; i ++ ) {
20+ const [ x , y ] = queue [ i ]
21+ for ( let j = 0 ; j < moves . length ; j ++ ) {
22+ const nextX = x + moves [ j ] [ 0 ]
23+ const nextY = y + moves [ j ] [ 1 ]
24+ if ( nextX >= 0 && nextY >= 0 && nextX < n && nextY < m ) {
25+ if ( dp [ nextX ] [ nextY ] > dp [ x ] [ y ] + ( grid [ x ] [ y ] - 1 === j ? 0 : 1 ) ) {
26+ dp [ nextX ] [ nextY ] = dp [ x ] [ y ] + ( grid [ x ] [ y ] - 1 === j ? 0 : 1 )
27+ queue . push ( [ nextX , nextY ] )
28+ }
29+ }
30+ }
31+ }
32+ queue = temp
33+ }
34+ return dp [ n - 1 ] [ m - 1 ]
35+ }
You can’t perform that action at this time.
0 commit comments