Minimum Cost Path with Alternating Directions I - Problem

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).

The path will always begin by entering cell (0, 0) on move 1 and paying the entrance cost. At each step, you move to an adjacent cell, following an alternating pattern:

  • On odd-numbered moves, you must move either right or down
  • On even-numbered moves, you must move either left or up

Return the minimum total cost required to reach (m - 1, n - 1). If it is impossible, return -1.

Input & Output

Example 1 — Small 2x2 Grid
$ Input: m = 2, n = 2
Output: 10
💡 Note: Start at (0,0) cost=1. Path: (0,0)→(0,1)→(0,0)→(1,0)→(1,1). Costs: 1+2+1+2+4=10
Example 2 — Simple 1x2 Grid
$ Input: m = 1, n = 2
Output: 3
💡 Note: Start at (0,0) cost=1, move right to (0,1) cost=2. Total: 1+2=3
Example 3 — Impossible Case
$ Input: m = 3, n = 3
Output: -1
💡 Note: With alternating movement rules, reaching (2,2) becomes impossible from (0,0)

Constraints

  • 1 ≤ m, n ≤ 103
  • Grid cells have cost (i+1) * (j+1)

Visualization

Tap to expand
Minimum Cost Path with Alternating Directions INPUT 1 (0,0) 2 (0,1) 2 (1,0) 4 (1,1) START END Cost formula: (i+1) * (j+1) m = 2 n = 2 Odd: Right/Down Even: Left/Up ALGORITHM STEPS 1 Start at (0,0) Move 1 (odd): Pay cost=1 2 Move Right to (0,1) Move 1: Pay cost=2 3 Move Left to (0,0) Move 2 (even): Pay cost=1 4 Move Down to (1,0) Move 3 (odd): Pay cost=2 5 Move Right to (1,1) Move 3: Pay cost=4 Optimal Path: (0,0)-->(0,1)-->(0,0) -->(1,0)-->(1,1) FINAL RESULT 1 2 3 4 5 Cost Breakdown: Step 1: (0,0) = 1 Step 2: (0,1) = 2 Step 3: (0,0) = 1 Step 4: (1,0) = 2 Step 5: (1,1) = 4 Total: 1+2+1+2+4 = 10 Output: 10 Key Insight: The alternating direction constraint means we cannot always take the direct path. Sometimes we must backtrack to eventually reach the goal. BFS/DP with state (row, col, move_parity) finds optimal path. For 2x2 grid, path (0,0)-->(0,1)-->(0,0)-->(1,0)-->(1,1) costs 1+2+1+2+4 = 10. TutorialsPoint - Minimum Cost Path with Alternating Directions I | Optimal Solution
Asked in
Google 15 Microsoft 12
8.5K Views
Medium Frequency
~25 min Avg. Time
180 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen