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
rcostrowCosts[r] - Horizontal moves (left/right) into column
ccostcolCosts[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
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!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code