Similar Problems
Similar Problems not available
Minimum Cost Homecoming Of A Robot In A Grid - Leetcode Solution
Companies:
LeetCode: Minimum Cost Homecoming Of A Robot In A Grid Leetcode Solution
Difficulty: Medium
Problem Statement: Given a grid of size m x n, where each cell contains a positive integer, representing the cost to traverse through that cell, starting from the top-left corner and ending at the bottom-right corner. A robot can only move right or down in the grid. Find the minimum cost to come back to the top-left corner from the bottom-right corner.
Solution:
Approach: We can start from the bottom-right corner and try to reach the top-left corner using dynamic programming.
For this, we can calculate the minimum cost to reach each cell of the grid from the bottom-right corner. We can use a 2D matrix to store the minimum cost for each cell.
To calculate the minimum cost for a particular cell, we need to consider the cost of the current cell and the minimum cost of the two adjacent cells (right and down).
Once we have calculated the minimum cost for each cell, we can use this to calculate the minimum cost to come back to the top-left corner from the bottom-right corner.
Algorithm:
-
Initialize a 2D matrix dp with size (m+1) x (n+1) and set dp[m][n] = grid[m-1][n-1], because this is the minimum cost to reach the bottom-right corner from itself.
-
Initialize the last row and last column of the dp matrix.
dp[i][n] = dp[i+1][n] + grid[i-1][n-1] for n = n-1 to 1
dp[m][j] = dp[m][j+1] + grid[m-1][j-1] for m = m-1 to 1
- Now, fill the remaining cells of the dp matrix by taking minimum of dp[i+1][j] and dp[i][j+1].
dp[i][j] = min(dp[i+1][j], dp[i][j+1]) + grid[i-1][j-1]
- The minimum cost to come back to the top-left corner is dp[1][1].
Code:
public int minCost(int[][] grid) { int m = grid.length; int n = grid[0].length; int[][] dp = new int[m+1][n+1]; dp[m][n] = grid[m-1][n-1]; for (int i = m-1; i >= 1; i--) { dp[i][n] = dp[i+1][n] + grid[i-1][n-1]; } for (int i = n-1; i >= 1; i--) { dp[m][i] = dp[m][i+1] + grid[m-1][i-1]; } for (int i = m-1; i >= 1; i--) { for (int j = n-1; j >= 1; j--) { dp[i][j] = Math.min(dp[i+1][j], dp[i][j+1]) + grid[i-1][j-1]; } } return dp[1][1]; }
Minimum Cost Homecoming Of A Robot In A Grid Solution Code
1