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 can not 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.
r, then this move costs rowCosts[r].c, then this move costs colCosts[c].Return the minimum total cost for this robot to return home.
Example 1:
Input: startPos = [1, 0], homePos = [2, 3], rowCosts = [5, 4, 3], colCosts = [8, 2, 6, 7] Output: 18 Explanation: One optimal path is that: Starting from (1, 0) -> It goes down to (2, 0). This move costs rowCosts[2] = 3. -> It goes right to (2, 1). This move costs colCosts[1] = 2. -> It goes right to (2, 2). This move costs colCosts[2] = 6. -> It goes right to (2, 3). This move costs colCosts[3] = 7. The total cost is 3 + 2 + 6 + 7 = 18
Example 2:
Input: startPos = [0, 0], homePos = [0, 0], rowCosts = [5], colCosts = [26] Output: 0 Explanation: The robot is already at its home. Since no moves occur, the total cost is 0.
Constraints:
m == rowCosts.lengthn == colCosts.length1 <= m, n <= 1050 <= rowCosts[r], colCosts[c] <= 104startPos.length == 2homePos.length == 20 <= startrow, homerow < m0 <= startcol, homecol < nWhen you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
To find the cheapest way to guide a robot to its final destination, the brute force approach is to map out every single path the robot could possibly take across the grid. By calculating the movement costs for each unique route from the starting position to the ending position, we can compare them all side by side.
Here's how the algorithm would work step-by-step:
def min_cost_homecoming(start_pos, home_pos, row_costs, col_costs):
# We generate all paths recursively to explore every possible route from start to finish
def explore_all_routes(current_row, current_column):
if current_row == home_pos[0] and current_column == home_pos[1]:
return [[]]
all_possible_paths = []
if current_row < home_pos[0]:
for generated_path in explore_all_routes(current_row + 1, current_column):
all_possible_paths.append([('down', current_row + 1)] + generated_path)
elif current_row > home_pos[0]:
for generated_path in explore_all_routes(current_row - 1, current_column):
all_possible_paths.append([('up', current_row - 1)] + generated_path)
if current_column < home_pos[1]:
for generated_path in explore_all_routes(current_row, current_column + 1):
all_possible_paths.append([('right', current_column + 1)] + generated_path)
elif current_column > home_pos[1]:
for generated_path in explore_all_routes(current_row, current_column - 1):
all_possible_paths.append([('left', current_column - 1)] + generated_path)
return all_possible_paths
all_computed_paths = explore_all_routes(start_pos[0], start_pos[1])
minimum_total_cost = float('inf')
# We evaluate every single path to find the one that accumulates the absolute lowest cost
for candidate_path in all_computed_paths:
current_path_cost = 0
for movement_direction, target_index in candidate_path:
if movement_direction in ('down', 'up'):
current_path_cost += row_costs[target_index]
else:
current_path_cost += col_costs[target_index]
if current_path_cost < minimum_total_cost:
minimum_total_cost = current_path_cost
return minimum_total_cost if all_computed_paths else 0Instead of trying every possible path through the grid, the optimal strategy recognizes that the robot must travel a specific horizontal and vertical distance regardless of the path it takes. By simply paying the toll for every step along the most direct path between the start and finish, we automatically achieve the absolute minimum total cost.
Here's how the algorithm would work step-by-step:
def min_cost(start_pos, home_pos, row_costs, col_costs):
total_cost_accumulated = 0
# Determine starting and ending row indices based on direction.
if start_pos[0] < home_pos[0]:
row_range = range(start_pos[0] + 1, home_pos[0] + 1)
else:
row_range = range(start_pos[0] - 1, home_pos[0] - 1, -1)
# Accumulate costs for each step along the direct vertical path.
for current_row in row_range:
total_cost_accumulated += row_costs[current_row]
# Determine starting and ending column indices based on direction.
if start_pos[1] < home_pos[1]:
col_range = range(start_pos[1] + 1, home_pos[1] + 1)
else:
col_range = range(start_pos[1] - 1, home_pos[1] - 1, -1)
# Accumulate costs for each step along the direct horizontal path.
for current_col in col_range:
total_cost_accumulated += col_costs[current_col]
return total_cost_accumulated| Case | How to Handle |
|---|---|
| Start position is already equal to home position | The distance calculations evaluate to zero and the function immediately returns a total cost of zero. |
| Robot only needs to move horizontally or vertically | The absent dimension contributes zero steps, naturally isolating the cost sum to the required axis. |
| Movement costs contain zero or negative values | Greedy addition simply accumulates all traversed cost indices without restriction since any intermediate path is valid. |
| Grid dimensions are at their minimum constraints of one row and one column | Array indexing remains safe and direct subtraction handles the single-cell coordinate lookup without out-of-bounds errors. |
| Grid dimensions are at their maximum constraints | The optimal O(N + M) arithmetic approach executes well within time limits without exceeding memory limits. |
| Movement costs array contains extremely large integer values | Using standard 64-bit integer types prevents potential arithmetic overflow during cost summation. |
| Start index is greater than home index requiring reverse traversal | The range summation logic correctly iterates backwards through the cost array to accumulate intermediate steps. |
| Multiple valid paths exist between start and home positions | Since all orthogonal paths between two grid points incur the exact same subset of row and column costs, any path yields the same minimum total. |