Min Cost Path in Grid with Right, Down and Diagonal Moves
Last Updated : 17 Oct, 2026
Given a matrix cost[][] of size n x m. Each cell contains a value that represents the cost to move through that cell.
You start at the top-left cell (0,0) and must reach the bottom-right cell (n-1, m-1).
From any cell (i, j), you can move to (i, j+1), (i+1, j), or (i+1, j+1).
Find the minimum cost required to reach the bottom-right corner. The cost of a path is the sum of all values on the path including both the start and end cells.
[Naive Approach] Recursion - O(3 ^ (m * n)) Time and O(1) Space
In this problem, we need to move from the starting cell (0,0) to the last cell (m-1, n-1). From every cell, we have three choices: we can move down (i+1, j), right (i, j+1), or diagonally (i+1, j+1). Whenever a problem gives multiple choices at every step, the first natural approach that comes to mind is recursion, because recursion allows us to break the problem into smaller independent subproblems.
To solve this using recursion, we start from the starting cell (0,0) and at each step we try all three possible moves.
Each recursive call represents taking one of the paths, and since we want the minimum cost path, we simply try all possibilities and take the minimum among them.
The base case occurs when the recursion reaches the last cell (m-1, n-1) - at that point, we stop and return the cost of that cell because the destination is reached.
C++
#include<iostream>#include<vector>usingnamespacestd;// Function to return the cost of the minimum cost pathintfindMinCost(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>=n){returnINT_MAX;}// Base case: bottom cellif(x==m-1&&y==n-1){returncost[x][y];}// Recursively calculate minimum cost from // all possible pathsintright=findMinCost(cost,x,y+1);intdown=findMinCost(cost,x+1,y);intdiag=findMinCost(cost,x+1,y+1);intbest=min(right,min(down,diag));returncost[x][y]+best;}// 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.Arrays;publicclassGFG{// Function to return the cost of the minimum cost pathstaticintfindMinCost(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 pathsintright=findMinCost(cost,x,y+1);intdown=findMinCost(cost,x+1,y);intdiag=findMinCost(cost,x+1,y+1);intbest=Math.min(right,Math.min(down,diag));returncost[x][y]+best;}// 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 pathdeffindMinCost(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 pathsright=findMinCost(cost,x,y+1)down=findMinCost(cost,x+1,y)diag=findMinCost(cost,x+1,y+1)best=min(right,down,diag)returncost[x][y]+best# Function to find the minimum cost path# to reach (m - 1, n - 1) from (0, 0)defminCost(cost):returnfindMinCost(cost,0,0)if__name__=="__main__":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 pathstaticintfindMinCost(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 pathsintright=findMinCost(cost,x,y+1);intdown=findMinCost(cost,x+1,y);intdiag=findMinCost(cost,x+1,y+1);intbest=Math.Min(right,Math.Min(down,diag));returncost[x,y]+best;}// Function to find the minimum cost path// to reach (m - 1, n - 1) from (0, 0)staticintminCost(int[,]cost){returnfindMinCost(cost,0,0);}staticvoidMain(){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 pathfunctionfindMinCost(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-right cellif(x===m-1&&y===n-1){returncost[x][y];}// Recursively calculate minimum cost for right, down and diagonalletright=findMinCost(cost,x,y+1);letdown=findMinCost(cost,x+1,y);letdiag=findMinCost(cost,x+1,y+1);// Find the minimum among the three pathsletbest=right;if(down<best)best=down;if(diag<best)best=diag;returncost[x][y]+best;}// Function to find the minimum cost path// to reach (m - 1, n - 1) from (0, 0)functionminCost(cost){returnfindMinCost(cost,0,0);}// Driver Codeletcost=[[1,2,3],[4,8,2],[1,5,3]];console.log(minCost(cost));
Output
8
[Better Approach - 1] 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++
#include<iostream>usingnamespacestd;intminCost(vector<vector<int>>&cost){intm=cost.size();intn=cost[0].size();vector<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});while(!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.Arrays;importjava.util.PriorityQueue;publicclassGFG{publicstaticintminCost(int[][]cost){intm=cost.length;intn=cost[0].length;int[][]directions={{1,0},{0,1},{1,1}};// Min-heap (priority queue) for Dijkstra's algorithmPriorityQueue<int[]>pq=newPriorityQueue<>((a,b)->Integer.compare(a[0],b[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});while(!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}};System.out.println(minCost(cost));}}
Python
importheapqimportsysdefminCost(cost):m=len(cost)n=len(cost[0])directions=[(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=[[sys.maxsize]*nfor_inrange(m)]dist[0][0]=cost[0][0]heapq.heappush(pq,(cost[0][0],0,0))whilepq:currCost,x,y=heapq.heappop(pq)# If we reached the bottom-right corner, return the costifx==m-1andy==n-1:returndist[x][y]# Explore 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]if__name__=="__main__":cost=[[1,2,3],[4,8,2],[1,5,3]]print(minCost(cost))
C#
usingSystem;usingSystem.Collections.Generic;classGFG{publicstaticintminCost(int[,]cost){intm=cost.GetLength(0);intn=cost.GetLength(1);int[][]directions=newint[][]{newint[]{1,0},newint[]{0,1},newint[]{1,1}};// Min-heap (priority queue) for Dijkstra's algorithmvarpq=newPriorityQueue<(int,int,int),int>();// 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.Enqueue((cost[0,0],0,0),cost[0,0]);while(pq.Count>0){varcurr=pq.Dequeue();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 neighborsforeach(vardirindirections){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.Enqueue((dist[newX,newY],newX,newY),dist[newX,newY]);}}}}returndist[m-1,n-1];}staticvoidMain(){int[,]cost={{1,2,3},{4,8,2},{1,5,3}};Console.WriteLine(minCost(cost));}}
JavaScript
functionminCost(cost){constm=cost.length;constn=cost[0].length;constdirections=[[1,0],[0,1],[1,1]];// Min-heap (priority queue) for Dijkstra's algorithmconstpq=[[cost[0][0],0,0]];// Distance matrix to store the minimum// cost to reach each cellconstdist=Array.from({length:m},()=>Array(n).fill(Number.MAX_SAFE_INTEGER));dist[0][0]=cost[0][0];pq.sort((a,b)=>a[0]-b[0]);while(pq.length>0){constcurr=pq.shift();constx=curr[1];consty=curr[2];// If we reached the bottom-right// corner, return the costif(x===m-1&&y===n-1){returndist[x][y];}// Explore the neighborsfor(constdirofdirections){constnewX=x+dir[0];constnewY=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.push([dist[newX][newY],newX,newY]);pq.sort((a,b)=>a[0]-b[0]);}}}}returndist[m-1][n-1];}// Driver Codeconstcost=[[1,2,3],[4,8,2],[1,5,3]];console.log(minCost(cost));
Output
8
[Better Approach - 2] Top-Down DP (Memoization) - O(m * n) Time and O(m * n) Space
If we look at the recursion tree, we notice that in recursion approach, many subproblems are solved again and again, which increases the time complexity. To handle this, we use a DP (memoization) approach. The idea is to store previously computed results in a DP table.
We create a 2D DP table of size (m × n) because there are two parameters that change in the recursive approach. After computing a subproblem, we store the result in the table. Later, when we encounter the same subproblem again, we check the table first. If the result is already computed, we return it instead of solving it again.
C++
#include<iostream>#include<vector>usingnamespacestd;// Function to return the cost of the minimum cost pathintfindMinCost(vector<vector<int>>&cost,intx,inty,vector<vector<int>>&dp){intm=cost.size();intn=cost[0].size();// If indices are out of bounds, return a large valueif(x>=m||y>=n){returnINT_MAX;}// Base case: bottom cellif(x==m-1&&y==n-1){returncost[x][y];}// Check if the result is already computedif(dp[x][y]!=-1){returndp[x][y];}intright=findMinCost(cost,x,y+1,dp);intdown=findMinCost(cost,x+1,y,dp);intdiag=findMinCost(cost,x+1,y+1,dp);intbest=min(right,min(down,diag));returndp[x][y]=cost[x][y]+best;}// 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>>dp(m,vector<int>(n,-1));returnfindMinCost(cost,0,0,dp);}intmain(){vector<vector<int>>cost={{1,2,3},{4,8,2},{1,5,3}};cout<<minCost(cost);return0;}
Java
importjava.util.Arrays;publicclassGFG{// Function to return the cost of the minimum cost pathstaticintfindMinCost(int[][]cost,intx,inty,int[][]dp){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(dp[x][y]!=-1)returndp[x][y];intright=findMinCost(cost,x,y+1,dp);intdown=findMinCost(cost,x+1,y,dp);intdiag=findMinCost(cost,x+1,y+1,dp);intbest=Math.min(right,Math.min(down,diag));returndp[x][y]=cost[x][y]+best;}// 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[][]dp=newint[m][n];for(int[]row:dp)Arrays.fill(row,-1);returnfindMinCost(cost,0,0,dp);}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 pathdeffindMinCost(cost,x,y,dp):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 computedifdp[x][y]!=-1:returndp[x][y]right=findMinCost(cost,x,y+1,dp)down=findMinCost(cost,x+1,y,dp)diag=findMinCost(cost,x+1,y+1,dp)best=min(right,down,diag)dp[x][y]=cost[x][y]+bestreturndp[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 pathdp=[[-1]*nfor_inrange(m)]returnfindMinCost(cost,0,0,dp)if__name__=="__main__":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 pathstaticintfindMinCost(int[,]cost,intx,inty,int[,]dp){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(dp[x,y]!=-1)returndp[x,y];intright=findMinCost(cost,x,y+1,dp);intdown=findMinCost(cost,x+1,y,dp);intdiag=findMinCost(cost,x+1,y+1,dp);intbest=Math.Min(right,Math.Min(down,diag));returndp[x,y]=cost[x,y]+best;}// 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[,]dp=newint[m,n];for(inti=0;i<m;i++)for(intj=0;j<n;j++)dp[i,j]=-1;returnfindMinCost(cost,0,0,dp);}staticvoidMain(){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 pathfunctionfindMinCost(cost,x,y,dp){constm=cost.length;constn=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(dp[x][y]!==-1)returndp[x][y];constright=findMinCost(cost,x,y+1,dp);constdown=findMinCost(cost,x+1,y,dp);constdiag=findMinCost(cost,x+1,y+1,dp);constbest=Math.min(right,down,diag);dp[x][y]=cost[x][y]+best;returndp[x][y];}// function to find the minimum cost path// to reach (m - 1, n - 1) from (0, 0)functionminCost(cost){constm=cost.length;constn=cost[0].length;// create 2d array to store the minimum cost pathconstdp=Array.from({length:m},()=>Array(n).fill(-1));returnfindMinCost(cost,0,0,dp);}// Driver Codeconstcost=[[1,2,3],[4,8,2],[1,5,3]];console.log(minCost(cost));
Output
8
[Better Approach - 3] Bottom-Up DP (Tabulation) - O(m * n) Time and O(m * n) Space
In the previous approach, we used recursion along with memoization. Even though memoization helps us avoid recomputing the same subproblems, the recursive structure still makes the solution slower and harder to manage for large inputs. To make the solution more efficient, we switch to a bottom-up dynamic programming method, where we build the answer iteratively.
The idea is simple: we directly fill a DP table step by step. First, we set the base case:
dp[0][0] = cost[0][0], because the starting cell’s minimum cost is just its own value.
First row: Since movement is only from the left, dp[0][j] = dp[0][j - 1] + cost[0][j] (for j > 0)
First column: Since movement is only from above, dp[i][0] = dp[i - 1][0] + cost[i][0] (for i > 0)
Once these base cases are set, the remaining table can be filled using the main DP relation. For every cell (i, j), we consider the minimum cost among the three possible ways to reach it and add the current cell’s cost to that minimum. By filling the table in this order, we ensure that all required subproblems are already solved when we need them.
C++
#include<iostream>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
classGFG{staticintminCost(int[][]cost){intm=cost.length;intn=cost[0].length;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]));}}returndp[m-1][n-1];}publicstaticvoidmain(String[]args){int[][]cost={{1,2,3},{4,8,2},{1,5,3}};System.out.println(minCost(cost));}}
Python
fromtypingimportListimportsysdefminCost(cost:List[List[int]])->int: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])returndp[m-1][n-1]if__name__=="__main__":cost=[[1,2,3],[4,8,2],[1,5,3]]print(minCost(cost))
C#
usingSystem;classGFG{staticintminCost(int[,]cost){intm=cost.GetLength(0);intn=cost.GetLength(1);int[,]dp=newint[m,n];// Base celldp[0,0]=cost[0,0];// Fill first rowfor(intj=1;j<n;j++){dp[0,j]=dp[0,j-1]+cost[0,j];}// Fill first columnfor(inti=1;i<m;i++){dp[i,0]=dp[i-1,0]+cost[i,0];}// Fill the rest of the 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]));}}returndp[m-1,n-1];}staticvoidMain(){int[,]cost={{1,2,3},{4,8,2},{1,5,3}};Console.WriteLine(minCost(cost));}}
JavaScript
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];}// Driver Codeconstcost=[[1,2,3],[4,8,2],[1,5,3]];console.log(minCost(cost));
Output
8
[Expected Approach] 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.
C++
#include<iostream>#include<vector>usingnamespacestd;intminCost(vector<vector<int>>&cost){intm=cost.size();intn=cost[0].size();vector<int>dp(n,0);dp[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++){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++){inttemp=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});prev=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
classGFG{staticintminCost(int[][]cost){intm=cost.length;intn=cost[0].length;int[]dp=newint[n];dp[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++){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++){inttemp=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));prev=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
defminCost(cost):m=len(cost)n=len(cost[0])dp=[0]*ndp[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):prev=dp[0]# Update the first column (only depends on# the previous row)dp[0]=dp[0]+cost[i][0]forjinrange(1,n):temp=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)prev=temp# The last cell contains the # minimum cost pathreturndp[n-1]if__name__=="__main__":cost=[[1,2,3],[4,8,2],[1,5,3]]print(minCost(cost))
C#
usingSystem;classGFG{staticintminCost(int[,]cost){intm=cost.GetLength(0);intn=cost.GetLength(1);int[]dp=newint[n];dp[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++){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++){inttemp=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));prev=temp;}}// The last cell contains the // minimum cost pathreturndp[n-1];}staticvoidMain(){int[,]cost={{1,2,3},{4,8,2},{1,5,3}};Console.WriteLine(minCost(cost));}}
JavaScript
functionminCost(cost){letm=cost.length;letn=cost[0].length;letdp=newArray(n).fill(0);dp[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++){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++){lettemp=dp[j];// Update dp[j] using the minimum of the// top, left, and diagonal cellsdp[j]=cost[i][j]+Math.min(dp[j],dp[j-1],prev);prev=temp;}}// The last cell contains the // minimum cost pathreturndp[n-1];}//Driver Codeletcost=[[1,2,3],[4,8,2],[1,5,3]];console.log(minCost(cost));