There is an m x n grid, where (0, 0) is the top-left cell and (m - 1, n - 1) is the bottom-right cell. You are given an integer array startPos where startPos = [startrow, startcol] indicates that initially, a robot is at the cell (startrow, startcol). You are also given an integer array homePos where homePos = [homerow, homecol] indicates that its home is at the cell (homerow, homecol).
The robot needs to go to its home. It can move one cell in four directions: left, right, up, or down, and it cannot move outside the boundary. Every move incurs some cost. You are further given two 0-indexed integer arrays: rowCosts of length m and colCosts of length n.
Movement cost rules:
• If the robot moves up or down into a cell whose row is r, then this move costs rowCosts[r].
• If the robot moves left or right into a cell whose column is c, then this move costs colCosts[c].
Return the minimum total cost for this robot to return home.
💡 Note:Move down from row 1 to row 2 (cost: rowCosts[2] = 3), then move right from col 0 to col 3 (costs: colCosts[1] + colCosts[2] + colCosts[3] = 2 + 6 + 7 = 15). Total: 3 + 15 = 18.
💡 Note:Move up from row 2 to row 1 (cost: rowCosts[1] = 7), then move left from col 2 to col 1 (cost: colCosts[1] = 1). But wait - we pay cost for the cell we enter. Moving up: we enter row 1, cost rowCosts[1] = 7. Moving left: we enter col 1, cost colCosts[1] = 1. Total: 7 + 1 = 8. Actually, let me recalculate: up to row 1 costs rowCosts[1]=7, left to col 1 costs colCosts[1]=1, total = 8. Wait, that doesn't match expected output of 4. Let me reconsider the movement costs...
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
Input Grid
Robot starts at position [1,0] and needs to reach home at [2,3]
2
Cost Analysis
Each move into a row/column has associated costs
3
Optimal Path
Direct path minimizes total movement cost
Key Takeaway
🎯 Key Insight: The direct path is always optimal since any detour adds unnecessary movement costs
Minimum Cost Homecoming of a Robot in a Grid — Solution
The key insight is that any detour from the direct path only adds unnecessary costs. The optimal approach is greedy: move directly from start to home position, calculating costs only for required movements. Time: O(m+n), Space: O(1)
Common Approaches
Approach
Time
Space
Notes
✓
Brute Force - Explore All Paths
O(4^(m+n))
O(m+n)
Use DFS to explore every possible path from start to home
Greedy - Direct Path
O(m+n)
O(1)
Move directly to destination using Manhattan distance path
Brute Force - Explore All Paths — Algorithm Steps
Start DFS from startPos
At each cell, try all 4 directions
Track minimum cost among all paths
Return the global minimum cost
Visualization
Tap to expand
Step-by-Step Walkthrough
1
Start DFS
Begin exploration from starting position
2
Try All Directions
At each cell, recursively explore all 4 directions
3
Track Minimum
Keep track of the minimum cost path found
Code -
solution.c — C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
#define MAX_VISITED 10000
struct Position {
int row, col;
};
struct Position visited[MAX_VISITED];
int visitedCount = 0;
int isVisited(int row, int col) {
for (int i = 0; i < visitedCount; i++) {
if (visited[i].row == row && visited[i].col == col) {
return 1;
}
}
return 0;
}
void addVisited(int row, int col) {
visited[visitedCount].row = row;
visited[visitedCount].col = col;
visitedCount++;
}
void removeVisited(int row, int col) {
for (int i = 0; i < visitedCount; i++) {
if (visited[i].row == row && visited[i].col == col) {
for (int j = i; j < visitedCount - 1; j++) {
visited[j] = visited[j + 1];
}
visitedCount--;
break;
}
}
}
int dfs(int row, int col, int* homePos, int* rowCosts, int rowSize, int* colCosts, int colSize) {
if (row == homePos[0] && col == homePos[1]) {
return 0;
}
if (isVisited(row, col)) {
return INT_MAX;
}
addVisited(row, col);
int minCost = INT_MAX;
// Try all 4 directions
int directions[4][2] = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
for (int i = 0; i < 4; i++) {
int newRow = row + directions[i][0];
int newCol = col + directions[i][1];
if (newRow >= 0 && newRow < rowSize && newCol >= 0 && newCol < colSize) {
int cost;
if (directions[i][0] == 0) { // horizontal move
cost = colCosts[newCol] + dfs(newRow, newCol, homePos, rowCosts, rowSize, colCosts, colSize);
} else { // vertical move
cost = rowCosts[newRow] + dfs(newRow, newCol, homePos, rowCosts, rowSize, colCosts, colSize);
}
if (cost != INT_MAX && cost < minCost) {
minCost = cost;
}
}
}
removeVisited(row, col);
return minCost;
}
int solution(int* startPos, int* homePos, int* rowCosts, int rowSize, int* colCosts, int colSize) {
visitedCount = 0;
return dfs(startPos[0], startPos[1], homePos, rowCosts, rowSize, colCosts, colSize);
}
int main() {
int startPos[2], homePos[2];
scanf("[%d,%d]", &startPos[0], &startPos[1]);
scanf("[%d,%d]", &homePos[0], &homePos[1]);
// Read rowCosts array - simplified parsing
int rowCosts[1000], rowSize = 0;
char c;
scanf(" %c", &c); // read '['
while (scanf("%d", &rowCosts[rowSize]) == 1) {
rowSize++;
scanf("%c", &c);
if (c == ']') break;
}
// Read colCosts array
int colCosts[1000], colSize = 0;
scanf(" %c", &c); // read '['
while (scanf("%d", &colCosts[colSize]) == 1) {
colSize++;
scanf("%c", &c);
if (c == ']') break;
}
printf("%d\n", solution(startPos, homePos, rowCosts, rowSize, colCosts, colSize));
return 0;
}
Time & Space Complexity
Time Complexity
⏱️
O(4^(m+n))
Each cell has 4 choices, path length up to m+n steps, leading to exponential paths
n
2n
✓ Linear Growth
Space Complexity
O(m+n)
Recursion call stack depth equals maximum path length of m+n moves
n
2n
⚡ Linearithmic Space
23.5K Views
MediumFrequency
~15 minAvg. Time
842 Likes
Ln 1, Col 1
Smart Actions
💡Explanation
AI Ready
💡 SuggestionTabto acceptEscto dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen
Algorithm Visualization
Pinch to zoom • Tap outside to close
Test Cases
0 passed
0 failed
3 pending
Select Compiler
Choose a programming language
Compiler list would appear here...
AI Editor Features
Header Buttons
💡
Explain
Get a detailed explanation of your code. Select specific code or analyze the entire file. Understand algorithms, logic flow, and complexity.
🔧
Fix
Automatically detect and fix issues in your code. Finds bugs, syntax errors, and common mistakes. Shows you what was fixed.
💡
Suggest
Get improvement suggestions for your code. Best practices, performance tips, and code quality recommendations.
💬
Ask AI
Open an AI chat assistant to ask any coding questions. Have a conversation about your code, get help with debugging, or learn new concepts.
Smart Actions (Slash Commands)
🔧
/fix Enter
Find and fix issues in your code. Detects common problems and applies automatic fixes.
💡
/explain Enter
Get a detailed explanation of what your code does, including time/space complexity analysis.
🧪
/tests Enter
Automatically generate unit tests for your code. Creates comprehensive test cases.
📝
/docs Enter
Generate documentation for your code. Creates docstrings, JSDoc comments, and type hints.
⚡
/optimize Enter
Get performance optimization suggestions. Improve speed and reduce memory usage.
AI Code Completion (Copilot-style)
👻
Ghost Text Suggestions
As you type, AI suggests code completions shown in gray text. Works with keywords like def, for, if, etc.
Tabto acceptEscto dismiss
💬
Comment-to-Code
Write a comment describing what you want, and AI generates the code. Try: # two sum, # binary search, # fibonacci
💡
Pro Tip: Select specific code before using Explain, Fix, or Smart Actions to analyze only that portion. Otherwise, the entire file will be analyzed.