LeetCode 2087: Minimum Cost Homecoming of a Robot in a Grid Solution
Master LeetCode problem 2087 (Minimum Cost Homecoming of a Robot in a Grid), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
Problem Explanation
Explanation
To solve this problem, we can use dynamic programming. We will create a 2D array to store the minimum cost of reaching each cell in the grid. We start from the startPos and iteratively calculate the minimum cost to reach each cell based on the costs of moving up, down, left, and right. Finally, we return the cost of reaching the homePos.
Here are the steps:
- Initialize a 2D array
dp[][]of size(m x n)to store the minimum cost to reach each cell. - Initialize
dp[startRow][startCol]as 0 since the robot is already at this position. - Iterate over all cells in the grid and update the minimum cost to reach each cell using the costs of moving up, down, left, and right.
- Return
dp[homeRow][homeCol]as the minimum total cost for the robot to return home.
The time complexity of this solution is O(m x n) where m is the number of rows and n is the number of columns in the grid. The space complexity is also O(m x n) for the 2D array dp.
Solution Code
class Solution {
public int minCost(int[] startPos, int[] homePos, int[] rowCosts, int[] colCosts) {
int m = rowCosts.length;
int n = colCosts.length;
int startRow = startPos[0];
int startCol = startPos[1];
int homeRow = homePos[0];
int homeCol = homePos[1];
int[][] dp = new int[m][n];
dp[startRow][startCol] = 0;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (i > 0) {
dp[i][j] = Math.min(dp[i][j] + rowCosts[i], dp[i - 1][j] + rowCosts[i]);
}
if (j > 0) {
dp[i][j] = Math.min(dp[i][j] + colCosts[j], dp[i][j - 1] + colCosts[j]);
}
}
}
return dp[homeRow][homeCol];
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 2087 (Minimum Cost Homecoming of a Robot in a Grid)?
This page provides optimized solutions for LeetCode problem 2087 (Minimum Cost Homecoming of a Robot in a Grid) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 2087 (Minimum Cost Homecoming of a Robot in a Grid)?
The time complexity for LeetCode 2087 (Minimum Cost Homecoming of a Robot in a Grid) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 2087 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2087 in Java, C++, or Python.