#3603

Minimum Cost Path with Alternating Directions II

Medium
ArrayDynamic ProgrammingMatrixDynamic ProgrammingGrid Traversal
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(m * n)
Space
O(1)
O(m * n)
💡

Intuition

Time O(m * n)Space O(m * n)

Use dynamic programming to store the minimum costs at each cell, alternating between moving and waiting. This avoids redundant calculations.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize a DP table to store minimum costs for each cell.
  2. 2Step 2: Fill the DP table by calculating costs based on previous cells and whether to wait or move.
  3. 3Step 3: Return the value in the bottom-right cell of the DP table.
solution.py12 lines
1def minCostPath(m, n, waitCost):
2    dp = [[float('inf')] * n for _ in range(m)]
3    dp[0][0] = 1
4    for i in range(m):
5        for j in range(n):
6            if i < m - 1:
7                dp[i + 1][j] = min(dp[i + 1][j], dp[i][j] + (i + 2) * (j + 1))
8            if j < n - 1:
9                dp[i][j + 1] = min(dp[i][j + 1], dp[i][j] + (i + 1) * (j + 2))
10            if i < m and j < n:
11                dp[i][j] += waitCost[i][j]
12    return dp[m - 1][n - 1]

Complexity note: The complexity comes from filling the DP table, iterating through each cell once.

  • 1Dynamic programming reduces redundant calculations.
  • 2Understanding the cost structure is crucial for optimal pathfinding.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.