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
Understanding the Visualization
1
Input
Grid dimensions m×n with cell costs (i+1)×(j+1)
2
Rules
Odd moves: right/down only. Even moves: left/up only
3
Output
Minimum cost to reach (m-1,n-1) or -1 if impossible
Key Takeaway
🎯 Key Insight: Alternating movement constraints severely limit reachability in larger grids
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code