You are given a 2D matrix cost[][] of dimensions m × n, where each cell represents the cost of traversing through that position. Your goal is to determine the minimum cost required to reach the bottom-right cell (m-1, n-1) starting from the top-left cell (0,0). The total cost of a path is the sum of all cell values along the path, including both the starting and ending positions. From any cell (i, j), you can move in the following three directions:
Right (i, j+1)
Down (i+1, j)
Diagonal (i+1, j+1)
Find the minimum cost path from (0,0) to (m-1, n-1), ensuring that movement constraints are followed.
Example:
Input:
Output: 8 Explanation: The path with minimum cost is highlighted in the following figure. The path is (0, 0) --> (0, 1) --> (1, 2) --> (2, 2). The cost of the path is 8 (1 + 2 + 2 + 3).
[Naive Approach] - Using Recursion - O(3 ^ (m * n)) Time and O(1) Space
The idea is to recursively generate all possible paths from top-left cell to bottom-right cell, and find the path with minimum cost. For the recursive approach, there are three potential cases for each cell in the grid (for any cell at position (m, n)):
The cost to reach the current cell can be calculated by moving left, i.e., from cell (m, n-1).
The cost to reach the current cell can also be calculated by moving up, i.e., from cell (m-1, n).
The cost can also be calculated by moving diagonally, i.e., from cell (m-1, n-1).
Mathematically, the recurrence relation will look like: minCost(cost, m, n) = cost[m][n] + min(minCost(cost, m, n-1), minCost(cost, m-1, n), minCost(cost, m-1, n-1))
Base Cases:
if m < 0 or n < 0 (out of bounds) minCost(cost, m, n) = INT_MAX
minCost(cost, 0, 0) = cost[0][0] as the starting point.
Below is given the implementation:
C++
#include<bits/stdc++.h>usingnamespacestd;// Function to return the cost of the minimum cost path// from (0,0) to (m - 1, n - 1) in a cost matrixintfindMinCost(vector<vector<int>>&cost,intx,inty){intm=cost.size();intn=cost[0].size();// If indices are out of bounds, return a large valueif(x>=m||y>=m){returnINT_MAX;}// Base case: bottom cellif(x==m-1&&y==n-1){returncost[x][y];}// Recursively calculate minimum cost from // all possible pathsreturncost[x][y]+min({findMinCost(cost,x,y+1),findMinCost(cost,x+1,y),findMinCost(cost,x+1,y+1)});}// function to find the minimum cost path// to reach (m - 1, n - 1) from (0, 0)intminCost(vector<vector<int>>&cost){returnfindMinCost(cost,0,0);}intmain(){vector<vector<int>>cost={{1,2,3},{4,8,2},{1,5,3}};cout<<minCost(cost);return0;}
Java
importjava.util.*;classGfG{// Function to return the cost of the minimum cost path// from (0,0) to (m - 1, n - 1) in a cost matrixstaticintfindMinCost(int[][]cost,intx,inty){intm=cost.length;intn=cost[0].length;// If indices are out of bounds, return a large valueif(x>=m||y>=n){returnInteger.MAX_VALUE;}// Base case: bottom cellif(x==m-1&&y==n-1){returncost[x][y];}// Recursively calculate minimum cost from // all possible pathsreturncost[x][y]+Math.min(Math.min(findMinCost(cost,x,y+1),findMinCost(cost,x+1,y)),findMinCost(cost,x+1,y+1));}// function to find the minimum cost path// to reach (m - 1, n - 1) from (0, 0)staticintminCost(int[][]cost){returnfindMinCost(cost,0,0);}publicstaticvoidmain(String[]args){int[][]cost={{1,2,3},{4,8,2},{1,5,3}};System.out.println(minCost(cost));}}
Python
importsys# Function to return the cost of the minimum cost path# from (0,0) to (m - 1, n - 1) in a cost matrixdeffindMinCost(cost,x,y):m=len(cost)n=len(cost[0])# If indices are out of bounds, return a large valueifx>=mory>=n:returnsys.maxsize# Base case: bottom cellifx==m-1andy==n-1:returncost[x][y]# Recursively calculate minimum cost from # all possible pathsreturncost[x][y]+min(findMinCost(cost,x,y+1),findMinCost(cost,x+1,y),findMinCost(cost,x+1,y+1))# function to find the minimum cost path# to reach (m - 1, n - 1) from (0, 0)defminCost(cost):returnfindMinCost(cost,0,0)cost=[[1,2,3],[4,8,2],[1,5,3]]print(minCost(cost))
C#
usingSystem;classGfG{// Function to return the cost of the minimum cost path// from (0,0) to (m - 1, n - 1) in a cost matrixstaticintfindMinCost(int[,]cost,intx,inty){intm=cost.GetLength(0);intn=cost.GetLength(1);// If indices are out of bounds, return a large valueif(x>=m||y>=n){returnint.MaxValue;}// Base case: bottom cellif(x==m-1&&y==n-1){returncost[x,y];}// Recursively calculate minimum cost from // all possible pathsreturncost[x,y]+Math.Min(Math.Min(findMinCost(cost,x,y+1),findMinCost(cost,x+1,y)),findMinCost(cost,x+1,y+1));}// function to find the minimum cost path// to reach (m - 1, n - 1) from (0, 0)staticintminCost(int[,]cost){returnfindMinCost(cost,0,0);}publicstaticvoidMain(){int[,]cost={{1,2,3},{4,8,2},{1,5,3}};Console.WriteLine(minCost(cost));}}
JavaScript
// Function to return the cost of the minimum cost path// from (0,0) to (m - 1, n - 1) in a cost matrixfunctionfindMinCost(cost,x,y){letm=cost.length;letn=cost[0].length;// If indices are out of bounds, return a large valueif(x>=m||y>=n){returnNumber.MAX_SAFE_INTEGER;}// Base case: bottom cellif(x===m-1&&y===n-1){returncost[x][y];}// Recursively calculate minimum cost from // all possible pathsreturncost[x][y]+Math.min(findMinCost(cost,x,y+1),findMinCost(cost,x+1,y),findMinCost(cost,x+1,y+1));}// function to find the minimum cost path// to reach (m - 1, n - 1) from (0, 0)functionminCost(cost){returnfindMinCost(cost,0,0);}letcost=[[1,2,3],[4,8,2],[1,5,3]];console.log(minCost(cost));
Output
8
[Expected Approach - 1] - Using Top-Down DP (Memoization) - O(m*n) Time and O(m*n) Space
1. Optimal Substructure:The minimum cost to reach any cell in the grid can be derived from smaller subproblems (i.e., the cost to reach neighboring cells). Specifically, the recursive relation will look like:
minCost(cost, m, n) = cost[m][n] + min(minCost(cost, m, n-1), minCost(cost, m-1, n), minCost(cost, m-1, n-1))
If the last element (i.e., cell (m - 1, n - 1)) is reached, the cost to reach it will be the value of the cell plus the minimum cost to reach one of its valid neighboring cells (left, up, or diagonal).
2. Overlapping Subproblems:
In the recursive approach, subproblems are computed multiple times. For example, when computing the minimum cost from (m, n), we may need to compute the cost for (m-1, n) multiple times. This repetition can be avoided by storing the results of subproblems in a memoization table.
Create a 2D memo table of size (m x n) to store the computed values, initialized to -1 to indicate uncomputed subproblems.
If we are at the last cell (m - 1, n - 1), return the value of cost[m - 1][n - 1].
Before computing the result for any cell (m, n), check if the value at memo[m][n] is already computed. If it is, return the stored value.
If the value is not computed, recursively calculate the minimum cost and store it in memo[m][n].
Finally, return the value in memo[0][0] for the minimum cost to reach the target cell (m-1, n-1).
Below is given the implementation:
C++
#include<bits/stdc++.h>usingnamespacestd;// Function to return the cost of the minimum cost path// from (0,0) to (m - 1, n - 1) in a cost matrixintfindMinCost(vector<vector<int>>&cost,intx,inty,vector<vector<int>>&memo){intm=cost.size();intn=cost[0].size();// If indices are out of bounds, return a large valueif(x>=m||y>=m){returnINT_MAX;}// Base case: bottom cellif(x==m-1&&y==n-1){returncost[x][y];}// Check if the result is already computedif(memo[x][y]!=-1){returnmemo[x][y];}// Recursively calculate minimum cost from // all possible pathsreturnmemo[x][y]=cost[x][y]+min({findMinCost(cost,x,y+1,memo),findMinCost(cost,x+1,y,memo),findMinCost(cost,x+1,y+1,memo)});}// function to find the minimum cost path// to reach (m - 1, n - 1) from (0, 0)intminCost(vector<vector<int>>&cost){intm=cost.size();intn=cost[0].size();// create 2d array to store the minimum cost pathvector<vector<int>>memo(m,vector<int>(n,-1));returnfindMinCost(cost,0,0,memo);}intmain(){vector<vector<int>>cost={{1,2,3},{4,8,2},{1,5,3}};cout<<minCost(cost);return0;}
Java
importjava.util.*;classGfG{// Function to return the cost of the minimum cost path// from (0,0) to (m - 1, n - 1) in a cost matrixstaticintfindMinCost(int[][]cost,intx,inty,int[][]memo){intm=cost.length;intn=cost[0].length;// If indices are out of bounds, return a large valueif(x>=m||y>=n){returnInteger.MAX_VALUE;}// Base case: bottom cellif(x==m-1&&y==n-1){returncost[x][y];}// Check if the result is already computedif(memo[x][y]!=-1){returnmemo[x][y];}// Recursively calculate minimum cost from // all possible pathsreturnmemo[x][y]=cost[x][y]+Math.min(Math.min(findMinCost(cost,x,y+1,memo),findMinCost(cost,x+1,y,memo)),findMinCost(cost,x+1,y+1,memo));}// function to find the minimum cost path// to reach (m - 1, n - 1) from (0, 0)staticintminCost(int[][]cost){intm=cost.length;intn=cost[0].length;// create 2d array to store the minimum cost pathint[][]memo=newint[m][n];for(int[]row:memo){Arrays.fill(row,-1);}returnfindMinCost(cost,0,0,memo);}publicstaticvoidmain(String[]args){int[][]cost={{1,2,3},{4,8,2},{1,5,3}};System.out.println(minCost(cost));}}
Python
importsys# Function to return the cost of the minimum cost path# from (0,0) to (m - 1, n - 1) in a cost matrixdeffindMinCost(cost,x,y,memo):m=len(cost)n=len(cost[0])# If indices are out of bounds, return a large valueifx>=mory>=n:returnsys.maxsize# Base case: bottom cellifx==m-1andy==n-1:returncost[x][y]# Check if the result is already computedifmemo[x][y]!=-1:returnmemo[x][y]# Recursively calculate minimum cost from # all possible pathsmemo[x][y]=cost[x][y]+min(findMinCost(cost,x,y+1,memo),findMinCost(cost,x+1,y,memo),findMinCost(cost,x+1,y+1,memo))returnmemo[x][y]# function to find the minimum cost path# to reach (m - 1, n - 1) from (0, 0)defminCost(cost):m=len(cost)n=len(cost[0])# create 2d array to store the minimum cost pathmemo=[[-1]*nfor_inrange(m)]returnfindMinCost(cost,0,0,memo)cost=[[1,2,3],[4,8,2],[1,5,3]]print(minCost(cost))
C#
usingSystem;classGfG{// Function to return the cost of the minimum cost path// from (0,0) to (m - 1, n - 1) in a cost matrixstaticintfindMinCost(int[,]cost,intx,inty,int[,]memo){intm=cost.GetLength(0);intn=cost.GetLength(1);// If indices are out of bounds, return a large valueif(x>=m||y>=n){returnint.MaxValue;}// Base case: bottom cellif(x==m-1&&y==n-1){returncost[x,y];}// Check if the result is already computedif(memo[x,y]!=-1){returnmemo[x,y];}// Recursively calculate minimum cost from // all possible pathsreturnmemo[x,y]=cost[x,y]+Math.Min(Math.Min(findMinCost(cost,x,y+1,memo),findMinCost(cost,x+1,y,memo)),findMinCost(cost,x+1,y+1,memo));}// function to find the minimum cost path// to reach (m - 1, n - 1) from (0, 0)staticintminCost(int[,]cost){intm=cost.GetLength(0);intn=cost.GetLength(1);// create 2d array to store the minimum cost pathint[,]memo=newint[m,n];for(inti=0;i<m;i++){for(intj=0;j<n;j++){memo[i,j]=-1;}}returnfindMinCost(cost,0,0,memo);}publicstaticvoidMain(){int[,]cost={{1,2,3},{4,8,2},{1,5,3}};Console.WriteLine(minCost(cost));}}
JavaScript
// Function to return the cost of the minimum cost path// from (0,0) to (m - 1, n - 1) in a cost matrixfunctionfindMinCost(cost,x,y,memo){letm=cost.length;letn=cost[0].length;// If indices are out of bounds, return a large valueif(x>=m||y>=n){returnNumber.MAX_SAFE_INTEGER;}// Base case: bottom cellif(x===m-1&&y===n-1){returncost[x][y];}// Check if the result is already computedif(memo[x][y]!==-1){returnmemo[x][y];}// Recursively calculate minimum cost from // all possible pathsreturnmemo[x][y]=cost[x][y]+Math.min(findMinCost(cost,x,y+1,memo),findMinCost(cost,x+1,y,memo),findMinCost(cost,x+1,y+1,memo));}// function to find the minimum cost path// to reach (m - 1, n - 1) from (0, 0)functionminCost(cost){letm=cost.length;letn=cost[0].length;// create 2d array to store the minimum cost pathletmemo=Array.from({length:m},()=>Array(n).fill(-1));returnfindMinCost(cost,0,0,memo);}letcost=[[1,2,3],[4,8,2],[1,5,3]];console.log(minCost(cost));
Output
8
[Expected Approach - 2] - Using Bottom-Up DP (Tabulation) -O(m * n) Time and O(m * n) Space
The approach here is similar to the recursive one but instead of breaking down the problem recursively, we iteratively build up the solution by calculating it in a bottom-up manner. We create a 2D array dp of size m*n where dp[i][j] represents the minimum cost to reach cell (i, j).
Dynamic Programming Relation:
Initialize the base case: dp[0][0] = cost[0][0]
For the first row (dp[0][j]), we can only move from the left: dp[0][j] = dp[0][j - 1] + cost[0][j] for j > 0
For the first column (dp[i][0]), we can only move from the top: dp[i][0] = dp[i - 1][0] + cost[i][0] for i > 0
For the rest of the cells, we calculate the minimum cost by considering the minimum cost from three directions: from the left, from above, and from the diagonal:
This formula ensures that at each step, we are choosing the minimum cost path to reach the current cell.
Below is given the implementation:
C++
// C++ implementation to find the minimum cost path// using Tabulation (Dynamic Programming)#include<bits/stdc++.h>usingnamespacestd;intminCost(vector<vector<int>>&cost){intm=cost.size();intn=cost[0].size();vector<vector<int>>dp(m,vector<int>(n,0));// Initialize the base celldp[0][0]=cost[0][0];// Fill the first rowfor(intj=1;j<n;j++){dp[0][j]=dp[0][j-1]+cost[0][j];}// Fill the first columnfor(inti=1;i<m;i++){dp[i][0]=dp[i-1][0]+cost[i][0];}// Fill the rest of the dp tablefor(inti=1;i<m;i++){for(intj=1;j<n;j++){dp[i][j]=cost[i][j]+min({dp[i-1][j],dp[i][j-1],dp[i-1][j-1]});}}returndp[m-1][n-1];}intmain(){vector<vector<int>>cost={{1,2,3},{4,8,2},{1,5,3}};cout<<minCost(cost);return0;}
Java
// Java implementation to find the minimum cost path// using Tabulation (Dynamic Programming)importjava.util.ArrayList;importjava.util.List;classGfG{staticintminCost(List<List<Integer>>cost){intm=cost.size();intn=cost.get(0).size();int[][]dp=newint[m][n];// Initialize the base celldp[0][0]=cost.get(0).get(0);// Fill the first rowfor(intj=1;j<n;j++){dp[0][j]=dp[0][j-1]+cost.get(0).get(j);}// Fill the first columnfor(inti=1;i<m;i++){dp[i][0]=dp[i-1][0]+cost.get(i).get(0);}// Fill the rest of the dp tablefor(inti=1;i<m;i++){for(intj=1;j<n;j++){dp[i][j]=cost.get(i).get(j)+Math.min(dp[i-1][j],Math.min(dp[i][j-1],dp[i-1][j-1]));}}// Minimum cost to reach the bottom-right cellreturndp[m-1][n-1];}publicstaticvoidmain(String[]args){List<List<Integer>>cost=newArrayList<>();cost.add(List.of(1,2,3));cost.add(List.of(4,8,2));cost.add(List.of(1,5,3));System.out.println(minCost(cost));}}
Python
# Python implementation to find the minimum cost path# using Tabulation (Dynamic Programming)defmincost(cost):m=len(cost)n=len(cost[0])dp=[[0]*nfor_inrange(m)]# Initialize the base celldp[0][0]=cost[0][0]# Fill the first rowforjinrange(1,n):dp[0][j]=dp[0][j-1]+cost[0][j]# Fill the first columnforiinrange(1,m):dp[i][0]=dp[i-1][0]+cost[i][0]# Fill the rest of the dp tableforiinrange(1,m):forjinrange(1,n):dp[i][j]=cost[i][j] \
+min(dp[i-1][j], \
dp[i][j-1],dp[i-1][j-1])# Minimum cost to reach the# bottom-right cellreturndp[m-1][n-1]if__name__=="__main__":cost=[[1,2,3],[4,8,2],[1,5,3]]print(mincost(cost))
C#
// C# implementation to find the minimum cost path// using Tabulation (Dynamic Programming)usingSystem;usingSystem.Collections.Generic;classGfG{staticintMinCost(List<List<int>>cost){intm=cost.Count;intn=cost[0].Count;int[,]dp=newint[m,n];// Initialize the base celldp[0,0]=cost[0][0];// Fill the first rowfor(intj=1;j<n;j++){dp[0,j]=dp[0,j-1]+cost[0][j];}// Fill the first columnfor(inti=1;i<m;i++){dp[i,0]=dp[i-1,0]+cost[i][0];}// Fill the rest of the dp tablefor(inti=1;i<m;i++){for(intj=1;j<n;j++){dp[i,j]=cost[i][j]+Math.Min(dp[i-1,j],Math.Min(dp[i,j-1],dp[i-1,j-1]));}}// Minimum cost to reach the// bottom-right cellreturndp[m-1,n-1];}staticvoidMain(){List<List<int>>cost=newList<List<int>>{newList<int>{1,2,3},newList<int>{4,8,2},newList<int>{1,5,3}};Console.WriteLine(MinCost(cost));}}
JavaScript
// JavaScript implementation to find the minimum cost path// using Tabulation (Dynamic Programming)functionminCost(cost){constm=cost.length;constn=cost[0].length;constdp=Array.from({length:m},()=>Array(n).fill(0));// Initialize the base celldp[0][0]=cost[0][0];// Fill the first rowfor(letj=1;j<n;j++){dp[0][j]=dp[0][j-1]+cost[0][j];}// Fill the first columnfor(leti=1;i<m;i++){dp[i][0]=dp[i-1][0]+cost[i][0];}// Fill the rest of the dp tablefor(leti=1;i<m;i++){for(letj=1;j<n;j++){dp[i][j]=cost[i][j]+Math.min(dp[i-1][j],dp[i][j-1],dp[i-1][j-1]);}}// Minimum cost to reach the bottom-right cellreturndp[m-1][n-1];}constcost=[[1,2,3],[4,8,2],[1,5,3]];console.log(minCost(cost));
Output
8
[Optimal Approach] - Using Space Optimized DP - O(m * n) Time and O(n) Space
In the previous approach, we used a 2D dp table to store the minimum cost at each cell. However, we can optimize the space complexity by observing that for calculating the current state, we only need the values from the previous row. Therefore, there is no need to store the entire dp table, and we can optimize the space to O(n) by only keeping track of the current and previous rows.
Below is given the implementation:
C++
// C++ implementation to find the minimum cost path// using Space Optimization#include<bits/stdc++.h>usingnamespacestd;intminCost(vector<vector<int>>&cost){intm=cost.size();intn=cost[0].size();// 1D dp array to store the minimum cost// of the current rowvector<int>dp(n,0);// Initialize the base celldp[0]=cost[0][0];// Fill the first rowfor(intj=1;j<n;j++){dp[j]=dp[j-1]+cost[0][j];}// Fill the rest of the rowsfor(inti=1;i<m;i++){// Store the previous value of dp[j-1] // (for diagonal handling)intprev=dp[0];// Update the first column (only depends on// the previous row)dp[0]=dp[0]+cost[i][0];for(intj=1;j<n;j++){// Store the current dp[j] before updating itinttemp=dp[j];// Update dp[j] using the minimum of the// top, left, and diagonal cellsdp[j]=cost[i][j]+min({dp[j],dp[j-1],prev});// Update prev to be the old dp[j] for the// diagonal calculation in the next iterationprev=temp;}}// The last cell contains the // minimum cost pathreturndp[n-1];}intmain(){vector<vector<int>>cost={{1,2,3},{4,8,2},{1,5,3}};cout<<minCost(cost)<<endl;return0;}
Java
// Java implementation to find the minimum cost path// using Space Optimizationimportjava.util.*;classGfG{staticintminCost(int[][]cost){intm=cost.length;intn=cost[0].length;// 1D dp array to store the minimum cost of the// current rowint[]dp=newint[n];// Initialize the base celldp[0]=cost[0][0];// Fill the first rowfor(intj=1;j<n;j++){dp[j]=dp[j-1]+cost[0][j];}// Fill the rest of the rowsfor(inti=1;i<m;i++){// Store the previous value of dp[j-1] (for// diagonal handling)intprev=dp[0];// Update the first column (only depends on the// previous row)dp[0]=dp[0]+cost[i][0];for(intj=1;j<n;j++){// Store the current dp[j] before updating// itinttemp=dp[j];// Update dp[j] using the minimum of the// top, left, and diagonal cellsdp[j]=cost[i][j]+Math.min(dp[j],Math.min(dp[j-1],prev));// Update prev to be the old dp[j] for the// diagonal calculation in the next// iterationprev=temp;}}// The last cell contains the minimum cost pathreturndp[n-1];}publicstaticvoidmain(String[]args){int[][]cost={{1,2,3},{4,8,2},{1,5,3}};System.out.println(minCost(cost));}}
Python
# Python implementation to find the minimum cost path# using Space OptimizationdefminCost(cost):m=len(cost)n=len(cost[0])# 1D dp array to store the minimum# cost of the current rowdp=[0]*n# Initialize the base celldp[0]=cost[0][0]# Fill the first rowforjinrange(1,n):dp[j]=dp[j-1]+cost[0][j]# Fill the rest of the rowsforiinrange(1,m):# Store the previous value of dp[j-1] # (for diagonal handling)prev=dp[0]# Update the first column (only depends# on the previous row)dp[0]=dp[0]+cost[i][0]forjinrange(1,n):# Store the current dp[j] before# updating ittemp=dp[j]# Update dp[j] using the minimum of the top,# left, and diagonal cellsdp[j]=cost[i][j]+min(dp[j],dp[j-1],prev)# Update prev to be the old dp[j] for the # diagonal calculation in the next iterationprev=temp# The last cell contains the minimum # cost pathreturndp[n-1]cost=[[1,2,3],[4,8,2],[1,5,3]]print(minCost(cost))
C#
// C# implementation to find the minimum cost path// using Space OptimizationusingSystem;classGfG{staticintMinCost(int[,]cost){intm=cost.GetLength(0);intn=cost.GetLength(1);// 1D dp array to store the minimum cost of the// current rowint[]dp=newint[n];// Initialize the base celldp[0]=cost[0,0];// Fill the first rowfor(intj=1;j<n;j++){dp[j]=dp[j-1]+cost[0,j];}// Fill the rest of the rowsfor(inti=1;i<m;i++){// Store the previous value of dp[j-1] (for// diagonal handling)intprev=dp[0];// Update the first column (only depends on the// previous row)dp[0]=dp[0]+cost[i,0];for(intj=1;j<n;j++){// Store the current dp[j] before updating// itinttemp=dp[j];// Update dp[j] using the minimum of the// top, left, and diagonal cellsdp[j]=cost[i,j]+Math.Min(dp[j],Math.Min(dp[j-1],prev));// Update prev to be the old dp[j] for the// diagonal calculation in the next// iterationprev=temp;}}// The last cell contains the minimum cost pathreturndp[n-1];}staticvoidMain(string[]args){int[,]cost={{1,2,3},{4,8,2},{1,5,3}};Console.WriteLine(MinCost(cost));}}
JavaScript
// JavaScript implementation to find the minimum cost path// using Space OptimizationfunctionminCost(cost){constm=cost.length;constn=cost[0].length;// 1D dp array to store the minimum cost of the current// rowletdp=newArray(n);// Initialize the base celldp[0]=cost[0][0];// Fill the first rowfor(letj=1;j<n;j++){dp[j]=dp[j-1]+cost[0][j];}// Fill the rest of the rowsfor(leti=1;i<m;i++){// Store the previous value of dp[j-1] (for diagonal// handling)letprev=dp[0];// Update the first column (only depends on the// previous row)dp[0]=dp[0]+cost[i][0];for(letj=1;j<n;j++){// Store the current dp[j] before updating itlettemp=dp[j];// Update dp[j] using the minimum of the top,// left, and diagonal cellsdp[j]=cost[i][j]+Math.min(dp[j],Math.min(dp[j-1],prev));// Update prev to be the old dp[j] for the// diagonal calculation in the next iterationprev=temp;}}// The last cell contains the minimum cost pathreturndp[n-1];}constcost=[[1,2,3],[4,8,2],[1,5,3]];console.log(minCost(cost));
Output
8
[Alternate Less Efficient Approach] - Using Dijkstra's Algorithm - O((m * n) * log(m * n)) Time and O(m * n) Space
The idea is to apply Dijskra's Algorithm to find the minimum cost path from the top-left to the bottom-right corner of the grid. Each cell is treated as a node and each move between adjacent cells has a cost. We use a min-heap to always expand the least costly path first.
C++
// C++ implementation to find minimum cost path// using Dijstra's Algoritms#include<bits/stdc++.h>usingnamespacestd;intminCost(vector<vector<int>>&cost){intm=cost.size();intn=cost[0].size();// Directions for moving down, right, and diagonalvector<pair<int,int>>directions={{1,0},{0,1},{1,1}};// Min-heap (priority queue) for Dijkstra's algorithmpriority_queue<vector<int>,vector<vector<int>>,greater<vector<int>>>pq;// Distance matrix to store the minimum// cost to reach each cellvector<vector<int>>dist(m,vector<int>(n,INT_MAX));dist[0][0]=cost[0][0];pq.push({cost[0][0],0,0});// Prim's algorithmwhile(!pq.empty()){vector<int>curr=pq.top();pq.pop();intx=curr[1];inty=curr[2];// If we reached the bottom-right // corner, return the costif(x==m-1&&y==n-1){returndist[x][y];}// Explore the neighborsfor(auto&dir:directions){intnewX=x+dir.first;intnewY=y+dir.second;// Ensure the new cell is within boundsif(newX<m&&newY<n){// Relaxation stepif(dist[newX][newY]>dist[x][y]+cost[newX][newY]){dist[newX][newY]=dist[x][y]+cost[newX][newY];pq.push({dist[newX][newY],newX,newY});}}}}returndist[m-1][n-1];}intmain(){vector<vector<int>>cost={{1,2,3},{4,8,2},{1,5,3}};cout<<minCost(cost);return0;}
Java
importjava.util.*;classGfG{intminCost(int[][]cost){intm=cost.length;intn=cost[0].length;// Directions for moving down, right, and diagonalint[][]directions={{1,0},{0,1},{1,1}};// Min-heap (priority queue) for Dijkstra's algorithmPriorityQueue<int[]>pq=newPriorityQueue<>(Comparator.comparingInt(a->a[0]));// Distance matrix to store the minimum// cost to reach each cellint[][]dist=newint[m][n];for(int[]row:dist){Arrays.fill(row,Integer.MAX_VALUE);}dist[0][0]=cost[0][0];pq.add(newint[]{cost[0][0],0,0});// Prim's algorithmwhile(!pq.isEmpty()){int[]curr=pq.poll();intx=curr[1];inty=curr[2];// If we reached the bottom-right // corner, return the costif(x==m-1&&y==n-1){returndist[x][y];}// Explore the neighborsfor(int[]dir:directions){intnewX=x+dir[0];intnewY=y+dir[1];// Ensure the new cell is within boundsif(newX<m&&newY<n){// Relaxation stepif(dist[newX][newY]>dist[x][y]+cost[newX][newY]){dist[newX][newY]=dist[x][y]+cost[newX][newY];pq.add(newint[]{dist[newX][newY],newX,newY});}}}}returndist[m-1][n-1];}publicstaticvoidmain(String[]args){int[][]cost={{1,2,3},{4,8,2},{1,5,3}};GfGobj=newGfG();System.out.println(obj.minCost(cost));}}
Python
importheapqdefminCost(cost):m=len(cost)n=len(cost[0])# Directions for moving down, right, and diagonaldirections=[(1,0),(0,1),(1,1)]# Min-heap (priority queue) for Dijkstra's algorithmpq=[]# Distance matrix to store the minimum# cost to reach each celldist=[[float('inf')]*nfor_inrange(m)]dist[0][0]=cost[0][0]heapq.heappush(pq,(cost[0][0],0,0))# Prim's algorithmwhilepq:curr=heapq.heappop(pq)x=curr[1]y=curr[2]# If we reached the bottom-right # corner, return the costifx==m-1andy==n-1:returndist[x][y]# Explore the neighborsfordx,dyindirections:newX=x+dxnewY=y+dy# Ensure the new cell is within boundsifnewX<mandnewY<n:# Relaxation stepifdist[newX][newY]>dist[x][y]+cost[newX][newY]:dist[newX][newY]=dist[x][y]+cost[newX][newY]heapq.heappush(pq,(dist[newX][newY],newX,newY))returndist[m-1][n-1]cost=[[1,2,3],[4,8,2],[1,5,3]]print(minCost(cost))
C#
usingSystem;usingSystem.Collections.Generic;classGfG{intminCost(int[,]cost){intm=cost.GetLength(0);intn=cost.GetLength(1);// Directions for moving down, right, and diagonalint[,]directions={{1,0},{0,1},{1,1}};// Min-heap (priority queue) for Dijkstra's algorithmSortedSet<(int,int,int)>pq=newSortedSet<(int,int,int)>(Comparer<(int,int,int)>.Create((a,b)=>a.Item1==b.Item1?(a.Item2==b.Item2?a.Item3-b.Item3:a.Item2-b.Item2):a.Item1-b.Item1));// Distance matrix to store the minimum// cost to reach each cellint[,]dist=newint[m,n];for(inti=0;i<m;i++){for(intj=0;j<n;j++){dist[i,j]=int.MaxValue;}}dist[0,0]=cost[0,0];pq.Add((cost[0,0],0,0));// Prim's algorithmwhile(pq.Count>0){varcurr=pq.Min;pq.Remove(curr);intx=curr.Item2;inty=curr.Item3;// If we reached the bottom-right // corner, return the costif(x==m-1&&y==n-1){returndist[x,y];}// Explore the neighborsfor(inti=0;i<3;i++){intnewX=x+directions[i,0];intnewY=y+directions[i,1];// Ensure the new cell is within boundsif(newX<m&&newY<n){// Relaxation stepif(dist[newX,newY]>dist[x,y]+cost[newX,newY]){dist[newX,newY]=dist[x,y]+cost[newX,newY];pq.Add((dist[newX,newY],newX,newY));}}}}returndist[m-1,n-1];}publicstaticvoidMain(){int[,]cost={{1,2,3},{4,8,2},{1,5,3}};GfGobj=newGfG();Console.WriteLine(obj.minCost(cost));}}
JavaScript
functionminCost(cost){letm=cost.length;letn=cost[0].length;// Directions for moving down, right, and diagonalletdirections=[[1,0],[0,1],[1,1]];// Min-heap (priority queue) for Dijkstra's algorithmletpq=[];// Distance matrix to store the minimum// cost to reach each cellletdist=Array.from({length:m},()=>Array(n).fill(Infinity));dist[0][0]=cost[0][0];pq.push([cost[0][0],0,0]);// Prim's algorithmwhile(pq.length>0){pq.sort((a,b)=>a[0]-b[0]);let[currCost,x,y]=pq.shift();// If we reached the bottom-right // corner, return the costif(x===m-1&&y===n-1){returndist[x][y];}// Explore the neighborsfor(let[dx,dy]ofdirections){letnewX=x+dx;letnewY=y+dy;// Ensure the new cell is within boundsif(newX<m&&newY<n){// Relaxation stepif(dist[newX][newY]>dist[x][y]+cost[newX][newY]){dist[newX][newY]=dist[x][y]+cost[newX][newY];pq.push([dist[newX][newY],newX,newY]);}}}}returndist[m-1][n-1];}console.log(minCost([[1,2,3],[4,8,2],[1,5,3]]));