Minimum Cost Homecoming of a Robot in a Grid - Problem

Imagine you have a robot on a grid that needs to get home! ๐Ÿค–

You're given an m ร— n grid where (0, 0) is the top-left corner and (m-1, n-1) is the bottom-right. Your robot starts at position startPos = [startrow, startcol] and needs to reach its home at homePos = [homerow, homecol].

The robot can move in four directions: up, down, left, or right (but can't go outside the grid boundaries). However, each move has a cost:

  • Vertical moves (up/down) into row r cost rowCosts[r]
  • Horizontal moves (left/right) into column c cost colCosts[c]

Your goal is to find the minimum total cost for the robot to reach home. Think of it like navigating through a city where different streets and avenues have different toll costs!

Input & Output

example_1.py โ€” Basic Case
$ Input: startPos = [1, 0], homePos = [2, 3], rowCosts = [5, 4, 3], colCosts = [8, 2, 6, 7]
โ€บ Output: 18
๐Ÿ’ก Note: Robot starts at (1,0) and needs to reach (2,3). It moves down to row 2 (cost 3), then right through columns 1,2,3 (costs 2+6+7=15). Total: 3+15=18.
example_2.py โ€” Same Position
$ Input: startPos = [0, 0], homePos = [0, 0], rowCosts = [5], colCosts = [26]
โ€บ Output: 0
๐Ÿ’ก Note: Robot is already at home, no movement needed, so cost is 0.
example_3.py โ€” Only Vertical Movement
$ Input: startPos = [1, 2], homePos = [3, 2], rowCosts = [2, 3, 4, 5], colCosts = [1, 6, 1]
โ€บ Output: 9
๐Ÿ’ก Note: Robot moves down from row 1 to row 3, passing through rows 2 and 3. Costs: 4 + 5 = 9. No column movement needed.

Constraints

  • m == rowCosts.length
  • n == colCosts.length
  • 1 โ‰ค m, n โ‰ค 105
  • 0 โ‰ค rowCosts[r], colCosts[c] โ‰ค 104
  • startPos.length == 2
  • homePos.length == 2
  • 0 โ‰ค startrow, homerow < m
  • 0 โ‰ค startcol, homecol < n

Visualization

Tap to expand
๐Ÿ START$3$2๐Ÿ HOMEDirect Path Cost: $3 + $2 = $5Any detour would only add more positive costs!๐Ÿ’ก Key InsightSince all costs are positive, the Manhattandistance path is always optimal!
Understanding the Visualization
1
Analyze Movement
Determine required row and column movements to reach home
2
Calculate Path Costs
Sum costs for each row and column cell entered
3
Verify Optimality
Any detour would add positive costs unnecessarily
Key Takeaway
๐ŸŽฏ Key Insight: Since all movement costs are positive, the direct path minimizing Manhattan distance is always optimal - any detour only adds unnecessary positive costs!
Asked in
Amazon 35 Google 28 Microsoft 22 Meta 18
25.4K Views
Medium Frequency
~15 min Avg. Time
847 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