LeetCode #3603 — MEDIUM

Minimum Cost Path with Alternating Directions II

Move from brute-force thinking to an efficient approach using array strategy.

Solve on LeetCode
The Problem

Problem Statement

You are given two integers m and n representing the number of rows and columns of a grid, respectively.

The cost to enter cell (i, j) is defined as (i + 1) * (j + 1).

You are also given a 2D integer array waitCost where waitCost[i][j] defines the cost to wait on that cell.

The path will always begin by entering cell (0, 0) on move 1 and paying the entrance cost.

At each step, you follow an alternating pattern:

  • On odd-numbered seconds, you must move right or down to an adjacent cell, paying its entry cost.
  • On even-numbered seconds, you must wait in place for exactly one second and pay waitCost[i][j] during that second.

Return the minimum total cost required to reach (m - 1, n - 1).

Example 1:

Input: m = 1, n = 2, waitCost = [[1,2]]

Output: 3

Explanation:

The optimal path is:

  • Start at cell (0, 0) at second 1 with entry cost (0 + 1) * (0 + 1) = 1.
  • Second 1: Move right to cell (0, 1) with entry cost (0 + 1) * (1 + 1) = 2.

Thus, the total cost is 1 + 2 = 3.

Example 2:

Input: m = 2, n = 2, waitCost = [[3,5],[2,4]]

Output: 9

Explanation:

The optimal path is:

  • Start at cell (0, 0) at second 1 with entry cost (0 + 1) * (0 + 1) = 1.
  • Second 1: Move down to cell (1, 0) with entry cost (1 + 1) * (0 + 1) = 2.
  • Second 2: Wait at cell (1, 0), paying waitCost[1][0] = 2.
  • Second 3: Move right to cell (1, 1) with entry cost (1 + 1) * (1 + 1) = 4.

Thus, the total cost is 1 + 2 + 2 + 4 = 9.

Example 3:

Input: m = 2, n = 3, waitCost = [[6,1,4],[3,2,5]]

Output: 16

Explanation:

The optimal path is:

  • Start at cell (0, 0) at second 1 with entry cost (0 + 1) * (0 + 1) = 1.
  • Second 1: Move right to cell (0, 1) with entry cost (0 + 1) * (1 + 1) = 2.
  • Second 2: Wait at cell (0, 1), paying waitCost[0][1] = 1.
  • Second 3: Move down to cell (1, 1) with entry cost (1 + 1) * (1 + 1) = 4.
  • Second 4: Wait at cell (1, 1), paying waitCost[1][1] = 2.
  • Second 5: Move right to cell (1, 2) with entry cost (1 + 1) * (2 + 1) = 6.

Thus, the total cost is 1 + 2 + 1 + 4 + 2 + 6 = 16.

Constraints:

  • 1 <= m, n <= 105
  • 2 <= m * n <= 105
  • waitCost.length == m
  • waitCost[0].length == n
  • 0 <= waitCost[i][j] <= 105
Patterns Used

Roadmap

  1. Brute Force Baseline
  2. Core Insight
  3. Algorithm Walkthrough
  4. Edge Cases
  5. Full Annotated Code
  6. Interactive Study Demo
  7. Complexity Analysis
Step 01

Brute Force Baseline

Problem summary: You are given two integers m and n representing the number of rows and columns of a grid, respectively. The cost to enter cell (i, j) is defined as (i + 1) * (j + 1). You are also given a 2D integer array waitCost where waitCost[i][j] defines the cost to wait on that cell. The path will always begin by entering cell (0, 0) on move 1 and paying the entrance cost. At each step, you follow an alternating pattern: On odd-numbered seconds, you must move right or down to an adjacent cell, paying its entry cost. On even-numbered seconds, you must wait in place for exactly one second and pay waitCost[i][j] during that second. Return the minimum total cost required to reach (m - 1, n - 1).

Baseline thinking

Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.

Pattern signal: Array · Dynamic Programming

Example 1

1
2
[[1,2]]

Example 2

2
2
[[3,5],[2,4]]

Example 3

2
3
[[6,1,4],[3,2,5]]
Step 02

Core Insight

What unlocks the optimal approach

  • Use dynamic programming
  • Observe that you need to wait at each cell except the first and last
  • Transition: <code>dp[i][j]</code> <- min(<code>dp[i‑1][j]</code>, <code>dp[i][j‑1]</code>) + <code>waitCost[i][j]</code> + (<code>i+1</code>)*(<code>j+1</code>)
  • The answer is <code>dp[m‑1][n‑1]</code> - <code>waitCost[m‑1][n‑1]</code>
Interview move: turn each hint into an invariant you can check after every iteration/recursion step.
Step 03

Algorithm Walkthrough

Iteration Checklist

  1. Define state (indices, window, stack, map, DP cell, or recursion frame).
  2. Apply one transition step and update the invariant.
  3. Record answer candidate when condition is met.
  4. Continue until all input is consumed.
Use the first example testcase as your mental trace to verify each transition.
Step 04

Edge Cases

Minimum Input
Single element / shortest valid input
Validate boundary behavior before entering the main loop or recursion.
Duplicates & Repeats
Repeated values / repeated states
Decide whether duplicates should be merged, skipped, or counted explicitly.
Extreme Constraints
Upper-end input sizes
Re-check complexity target against constraints to avoid time-limit issues.
Invalid / Corner Shape
Empty collections, zeros, or disconnected structures
Handle special-case structure before the core algorithm path.
Step 05

Full Annotated Code

Source-backed implementations are provided below for direct study and interview prep.

// Accepted solution for LeetCode #3603: Minimum Cost Path with Alternating Directions II
// Auto-generated Java example from go.
class Solution {
    public void exampleSolution() {
    }
}
// Reference (go):
// // Accepted solution for LeetCode #3603: Minimum Cost Path with Alternating Directions II
// package main
// 
// import "math"
// 
// // https://space.bilibili.com/206214
// func minCost1(m, n int, waitCost [][]int) int64 {
// 	memo := make([][]int, m)
// 	for i := range memo {
// 		memo[i] = make([]int, n)
// 	}
// 	var dfs func(int, int) int
// 	dfs = func(i, j int) (res int) {
// 		if i < 0 || j < 0 {
// 			return math.MaxInt
// 		}
// 		if i == 0 && j == 0 {
// 			return 1 // 起点只有 1 的进入成本,不需要等待
// 		}
// 		p := &memo[i][j]
// 		if *p == 0 {
// 			*p = min(dfs(i, j-1), dfs(i-1, j)) + waitCost[i][j] + (i+1)*(j+1)
// 		}
// 		return *p
// 	}
// 	return int64(dfs(m-1, n-1) - waitCost[m-1][n-1]) // 终点不需要等待
// }
// 
// func minCost2(m, n int, waitCost [][]int) int64 {
// 	f := make([][]int, m+1)
// 	for i := range f {
// 		f[i] = make([]int, n+1)
// 	}
// 	f[0][1] = -waitCost[0][0] // 计算 f[1][1] 的时候抵消掉
// 	for j := 2; j <= n; j++ {
// 		f[0][j] = math.MaxInt
// 	}
// 	for i, row := range waitCost {
// 		f[i+1][0] = math.MaxInt
// 		for j, c := range row {
// 			f[i+1][j+1] = min(f[i+1][j], f[i][j+1]) + c + (i+1)*(j+1)
// 		}
// 	}
// 	return int64(f[m][n] - waitCost[m-1][n-1])
// }
// 
// func minCost3(m, n int, waitCost [][]int) int64 {
// 	f := make([]int, n+1)
// 	for j := range f {
// 		f[j] = math.MaxInt
// 	}
// 	f[1] = -waitCost[0][0]
// 	for i, row := range waitCost {
// 		for j, c := range row {
// 			f[j+1] = min(f[j], f[j+1]) + c + (i+1)*(j+1)
// 		}
// 	}
// 	return int64(f[n] - waitCost[m-1][n-1])
// }
// 
// func minCost(m, n int, f [][]int) int64 {
// 	f[0][0] = 1
// 	f[m-1][n-1] = 0
// 	for j := 1; j < n; j++ {
// 		f[0][j] += f[0][j-1] + j + 1
// 	}
// 	for i := 1; i < m; i++ {
// 		f[i][0] += f[i-1][0] + i + 1
// 		for j := 1; j < n; j++ {
// 			f[i][j] += min(f[i][j-1], f[i-1][j]) + (i+1)*(j+1)
// 		}
// 	}
// 	return int64(f[m-1][n-1])
// }
Step 06

Interactive Study Demo

Use this to step through a reusable interview workflow for this problem.

Press Step or Run All to begin.
Step 07

Complexity Analysis

Time
O(n × m)
Space
O(n × m)

Approach Breakdown

RECURSIVE
O(2ⁿ) time
O(n) space

Pure recursion explores every possible choice at each step. With two choices per state (take or skip), the decision tree has 2ⁿ leaves. The recursion stack uses O(n) space. Many subproblems are recomputed exponentially many times.

DYNAMIC PROGRAMMING
O(n × m) time
O(n × m) space

Each cell in the DP table is computed exactly once from previously solved subproblems. The table dimensions determine both time and space. Look for the state variables — each unique combination of state values is one cell. Often a rolling array can reduce space by one dimension.

Shortcut: Count your DP state dimensions → that’s your time. Can you drop one? That’s your space optimization.
Coach Notes

Common Mistakes

Review these before coding to avoid predictable interview regressions.

Off-by-one on range boundaries

Wrong move: Loop endpoints miss first/last candidate.

Usually fails on: Fails on minimal arrays and exact-boundary answers.

Fix: Re-derive loops from inclusive/exclusive ranges before coding.

State misses one required dimension

Wrong move: An incomplete state merges distinct subproblems and caches incorrect answers.

Usually fails on: Correctness breaks on cases that differ only in hidden state.

Fix: Define state so each unique subproblem maps to one DP cell.