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
Alternating Direction Path Problem1224STARTTARGETMovement Rules:Odd: → ↓ onlyEven: ← ↑ onlyPath must alternate between these rule setsCell cost = (row+1) × (col+1)Find minimum cost path or return -1Many destinations become unreachable!
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
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