1
+ // 3603. Minimum Cost Path with Alternating Directions II
2
+ // You are given two integers m and n representing the number of rows and columns of a grid, respectively.
3
+ // The cost to enter cell (i, j) is defined as (i + 1) * (j + 1).
4
+ // You are also given a 2D integer array waitCost where waitCost[i][j] defines the cost to wait on that cell.
5
+ // The path will always begin by entering cell (0, 0) on move 1 and paying the entrance cost.
6
+ // At each step, you follow an alternating pattern:
7
+ // On odd-numbered seconds, you must move right or down to an adjacent cell, paying its entry cost.
8
+ // On even-numbered seconds, you must wait in place for exactly one second and pay waitCost[i][j] during that second.
9
+ // Return the minimum total cost required to reach (m - 1, n - 1).
10
+
11
+
12
+ // Solution: DP
13
+
14
+ // Essentially, it's a classic DP problem.
15
+ // We always have to pay two costs to reach a cell, the entry cost and the wait cost.
16
+ // dp[i][j] = min(dp[i - 1][j] + costs, dp[i][j - 1] + costs).
17
+
18
+ // The exception is the first cell, at which we don't have to wait on.
19
+
20
+ // Time Complexity: O(mn) 97ms
21
+ // Space Complexity: O(mn) 93MB
22
+ function minCost ( m , n , waitCost ) {
23
+ const dp = Array ( m ) . fill ( 0 ) . map ( ( ) => Array ( n ) ) ;
24
+ dp [ 0 ] [ 0 ] = 1 ;
25
+ for ( let i = 0 ; i < m ; i ++ ) {
26
+ for ( let j = 0 ; j < n ; j ++ ) {
27
+ if ( i === 0 && j === 0 ) continue ;
28
+ const up = i > 0 ? dp [ i - 1 ] [ j ] + getWaitCost ( i - 1 , j ) : Infinity ;
29
+ const left = j > 0 ? dp [ i ] [ j - 1 ] + getWaitCost ( i , j - 1 ) : Infinity ;
30
+ dp [ i ] [ j ] = ( i + 1 ) * ( j + 1 ) + Math . min ( up , left ) ;
31
+ }
32
+ }
33
+ return dp [ m - 1 ] [ n - 1 ] ;
34
+
35
+ function getWaitCost ( row , col ) {
36
+ if ( row === 0 && col === 0 ) {
37
+ return 0 ;
38
+ }
39
+ return waitCost [ row ] [ col ] ;
40
+ }
41
+ } ;
42
+
43
+ // Three test cases
44
+ console . log ( minCost ( 1 , 2 , [ [ 1 , 2 ] ] ) ) // 3
45
+ console . log ( minCost ( 2 , 2 , [ [ 3 , 5 ] , [ 2 , 4 ] ] ) ) // 9
46
+ console . log ( minCost ( 2 , 3 , [ [ 6 , 1 , 4 ] , [ 3 , 2 , 5 ] ] ) ) // 16
0 commit comments