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 topleft corner and ending at the bottomright corner. A robot can only move right or down in the grid. Find the minimum cost to come back to the topleft corner from the bottomright corner.
Solution:
Approach: We can start from the bottomright corner and try to reach the topleft corner using dynamic programming.
For this, we can calculate the minimum cost to reach each cell of the grid from the bottomright 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 topleft corner from the bottomright corner.
Algorithm:

Initialize a 2D matrix dp with size (m+1) x (n+1) and set dp[m][n] = grid[m1][n1], because this is the minimum cost to reach the bottomright corner from itself.

Initialize the last row and last column of the dp matrix.
dp[i][n] = dp[i+1][n] + grid[i1][n1] for n = n1 to 1
dp[m][j] = dp[m][j+1] + grid[m1][j1] for m = m1 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[i1][j1]
 The minimum cost to come back to the topleft 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[m1][n1]; for (int i = m1; i >= 1; i) { dp[i][n] = dp[i+1][n] + grid[i1][n1]; } for (int i = n1; i >= 1; i) { dp[m][i] = dp[m][i+1] + grid[m1][i1]; } for (int i = m1; i >= 1; i) { for (int j = n1; j >= 1; j) { dp[i][j] = Math.min(dp[i+1][j], dp[i][j+1]) + grid[i1][j1]; } } return dp[1][1]; }
Minimum Cost Homecoming Of A Robot In A Grid Solution Code
1