Minimum Cost Path | Practice | GeeksforGeeks

Given a square grid of size N, each cell of which contains integer cost which represents a cost to traverse through that cell, we need to find a path from top left cell to bottom right cell by which the total cost incurred is minimum.
From the cell (i,j) we can go (i,j-1), (i, j+1), (i-1, j), (i+1, j). 
Note: It is assumed that negative cost cycles do not exist in the input matrix.
 
Example 1:
Input: grid = {{9,4,9,9},{6,7,6,4},
{8,3,3,7},{7,4,9,10}}
Output: 43
Explanation: The grid is-
9 4 9 9
6 7 6 4
8 3 3 7
7 4 9 10
The minimum cost is-
9 + 4 + 7 + 3 + 3 + 7 + 10 = 43.

Example 2:
Input: grid = {{4,4},{3,7}}
Output: 14
Explanation: The grid is-
4 4
3 7
The minimum cost is- 4 + 3 + 7 = 14.

 
Your Task:
You don't need to read or print anything. Your task is to complete the function minimumCostPath() which takes grid as input parameter and returns the minimum cost to react at bottom right cell from top left cell.
 
Expected Time Compelxity: O(n2*log(n))
Expected Auxiliary Space: O(n2) 
 
Constraints:
1 ≤ n ≤ 500
1 ≤ cost of cells ≤ 1000
0
ghanshyamsinghal22in 10 hours
why this is showing runtime error please anyone help 
class Solution{   public:   //Function to return the minimum cost to react at bottom//right cell from top left cell.bool ok(int x,int y,int n,int m){    if((x>=0&&x<n)&&(y>=0&&y<m)){        return 1;    }    return 0;}   int minimumCostPath(vector<vector<int>>& grid) {       multiset<vector<int>> d;       vector<vector<int>> b;       int n = a.size();       int m = a[0].size();       int i;       for(i=0;i<n;i++){           vector <int> c (m,INT_MAX);           b.push_back(c);       }       d.insert({a[0][0],0,0});       while(d.size()){           vector <int> x= *d.begin();           if(b[x[1]][x[2]]>x[0]){               b[x[1]][x[2]]=x[0];                              d.erase(d.begin());               if(ok(x[1]-1,x[2],n,m)&&b[x[1]-1][x[2]]>x[0]+a[x[1]-1][x[2]]){                   d.insert({x[0]+a[x[1]-1][x[2]],x[1]-1,x[2]});               }               if(ok(x[1],x[2]+1,n,m)&&b[x[1]][x[2]+1]>x[0]+a[x[1]][x[2]+1]){                   d.insert({x[0]+a[x[1]][x[2]+1],x[1],x[2]+1});               }               if(ok(x[1]+1,x[2],n,m)&&b[x[1]+1][x[2]]>x[0]+a[x[1]+1][x[2]]){                   d.insert({x[0]+a[x[1]+1][x[2]],x[1]+1,x[2]});               }               if(ok(x[1],x[2]-1,n,m)&&b[x[1]][x[2]-1]>x[0]+a[x[1]][x[2]-1]){                   d.insert({x[0]+a[x[1]][x[2]-1],x[1],x[2]-1});               }           }else{               d.erase(d.begin());           }       }       // vector <int> x= *d.begin();       return b[n-1][m-1];   }};
0
trilokjain3 days ago
// i think this is best code for this but this give error at some edge case
 
 
class Solution{   public:   //Function to return the minimum cost to react at bottom//right cell from top left cell.int min_cost(int row,int column, vector<vector<int>>& grid, vector<vector<int>>& a,int n){    if(row==0 && column > 0)    {        return a[row][column]  = min_cost(row,column-1,grid,a,n)+grid[row][column];    }    if(column==0 && row > 0)    {        return a[row][column]  = min_cost(row-1,column,grid,a,n)+grid[row][column];    }    if( row < 0 || column<0||row>n-1 || column>n-1) return 0;        if(row==0 && column== 0) return  a[row][column]= grid[row][column];    if(a[row][column] != -1) return a[row][column];    int x=min_cost(row-1,column,grid,a,n);    int y  = min_cost(row,column-1,grid,a,n);       a[row][column] = min(x,y)+grid[row][column];    return a[row][column];}   int minimumCostPath(vector<vector<int>>& grid)    {       // Code here              int n= grid[0].size();              vector<vector<int>>a(n,vector<int>(n,-1));             return  min_cost(n-1,n-1,grid,a,n);   }};
+2
prashan1um5l5 days ago
C++ SOLUTION ;)
int n=grid.size();        int m=grid[0].size();        int ans=0;        int dist[n][m];        for(int i=0; i<n; i++){            for(int j=0; j<m; j++){                dist[i][j]=INT_MAX;            }        }priority_queue<pair<int, pair<int, int>>, vector<pair<int, pair<int, int>>>, greater<pair<int, pair<int, int>>>>pq;     dist[0][0]=grid[0][0];     pq.push({dist[0][0], {0, 0}});     int dx[4]={0, 0, -1, 1};     int dy[4]={-1, 1, 0, 0};     while(pq.empty()==false){         auto x=pq.top(); pq.pop();         int cost=x.first;         auto y=x.second;         int i=y.first;         int j=y.second;         ans+=cost;         if(i==n-1  && j==m-1){             break;         }         //visted[i][j]=true;         for(int k=0; k<4; k++){             int u=i+dx[k];             int v=j+dy[k];             if(u>=0 && u<n && v>=0 &&  v<m  ){                 if(dist[u][v]>=dist[i][j]+ grid[u][v]){                     dist[u][v]=dist[i][j]+grid[u][v];                     pq.push({dist[u][v], {u, v}});                 }             }         }     }     return dist[n-1][m-1];     //return ans;   }
0
mishraaman4356 days ago
java Dijkstra + shortest path
6-7 sec
class Solution{
    public int minimumCostPath(int[][] g){
        int n=g.length;
        int m=g[0].length;
        boolean [][] v= new boolean [n][m];
        int dx[]={1, -1, 0,0};
        int dy[]= {0,0,-1,1};
        PriorityQueue <pair> q= new PriorityQueue<pair>((e,f)->(e.z-f.z));
        q.offer(new pair(0,0,g[0][0]));
        while(!q.isEmpty()){
            pair c=q.poll();
            if(c.x==n-1 && c.y==m-1) return c.z;
            for(int i=0; i<4; i++){
                int a= c.x+dx[i];
                int b= c.y+dy[i];
                if(a>=n ||b>=m ||a<0 ||b<0 ||v[a][b]) continue;
                v[a][b]=true;
                q.offer(new pair(a,b,c.z+g[a][b]));
            }
        }
        return -1;
    }
    class pair{
        int x;
        int y;
        int z;
        pair(int x, int y, int z){
            this.x=x;
            this.y=y;
            this.z=z;
        }
    }
}
0
sidsahu09026 days ago
Can anyone help me, I am getting Runtime error in this code
int sol(int i, int j, vector<vector<int>>&grid, vector<vector<int>>&dp,int n){
 
    if(i>n-1 || j>n-1 || i<0 || j<0  ){
        return 1e6;
    }
    if(i==0 && j==0){
        return grid[i][j];
    }
    if(dp[i][j]!=-1){
        return dp[i][j];
    }
    int  up = grid[i][j] + sol(i-1, j, grid, dp, n);
    iny left = grid[i][j]+ sol(i, j-1, grid, dp, n);
    int right = grid[i][j] + sol(i, j+1, grid, dp, n);
    int down = grid[i][j] + sol(i+1, j, grid, dp, n);
    
    return dp[i][j]= min(left, min(right, min(up, down)));
    
}

   int minimumCostPath(vector<vector<int>>& grid) 
   {
       // Code here
       int n = grid[0].size();
       vector<vector<int>>dp(n, vector<int>(n, -1));
       return sol(n-1, n-1, grid, dp, n);
   }
0
gaurpiyush0011 week ago
Is this Problem can be by Backtracking???,If Yes then why we are using graph??
-1
dflag441 week ago
 can anyone tell problem in this approach
int helper(int i,int j,int n,int m,vector<vector<int>>&grid,vector<vector<int>>&dp, vector<vector<bool>>&vst){    if(i<0||j<0||i>n||j>m||vst[i][j])return 1000000;        if(dp[i][j]!=-1)return dp[i][j];        if(i==n && j==m)return grid[i][j];    vst[i][j]=true;    int x= grid[i][j]+min({        helper(i,j-1,n,m,grid,dp,vst),        helper(i,j+1,n,m,grid,dp,vst),        helper(i-1,j,n,m,grid,dp,vst),        helper(i+1,j,n,m,grid,dp,vst),            });        vst[i][j]=false;    return dp[i][j]= x;        }   int minimumCostPath(vector<vector<int>>& grid)    {       int n=grid.size();       int m=grid[0].size();       vector<vector<int>>dp(n,vector<int>(m,-1));       vector<vector<bool>>vst(n,vector<bool>(m,false));       n--;       m--;              return helper(0,0,n,m,grid,dp,vst);          }
-1
spiderman691 week ago
Code without using pairs
 
 struct cell{   int x;   int y;   int weight;   cell(int x,int y, int weight)   {       this->x = x;       this->y = y;       this->weight = weight;   } };    struct cellcomp{       bool operator()(cell c1,cell c2)       {           return c1.weight>c2.weight;       }   }; bool isvalid(int i, int j, int n) {     if(i>=0 && i<n && j>=0 && j<n)     {         return true;     }else     return false; }   int minimumCostPath(vector<vector<int>>& grid)    {       // Code        int node = grid.size();              vector<vector<bool>> visited(node,vector<bool>(node,false));       vector<vector<int>> weight(node,vector<int>(node,1e8));                   int xar[4] = {0,-1,0,1};       int yar[4] = {-1,0,1,0};              weight[0][0] = grid[0][0];       priority_queue<cell,vector<cell>,cellcomp> pq;       pq.push({0,0,grid[0][0]});              while(!pq.empty())       {           cell temp = pq.top();           pq.pop();                     int curr_x = temp.x;           int curr_y = temp.y;           if(visited[curr_x][curr_y])                     continue;                                 visited[curr_x][curr_y] = true;                  for(int i=0;i<4;i++)           {              int next_x = curr_x +xar[i];               int    next_y = curr_y + yar[i];                              if(isvalid(next_x,next_y,node) && !visited[next_x][next_y])               {                   if(weight[next_x][next_y] > (weight[curr_x][curr_y]+                               grid[next_x][next_y]))                   {                       weight[next_x][next_y]= weight[curr_x][curr_y]+ grid[next_x][next_y];                   }                                      pq.push({next_x,next_y,weight[next_x][next_y]});               }           }                             }       return weight[node-1][node-1];   }
-1
anuragtiwariug201 week ago
Anyone know why my code give runtime error
int t[1000][1000];int solve(int i,int j,vector<vector<int>> &grid){       if(i==grid.size()-1 && j==grid[0].size()-1)       {           return grid[i][j];       }       if(i>=grid.size()||j>=grid[0].size())       {           return 1e9;       }       if(t[i][j]!=-1)       {           return t[i][j];       }       int a=grid[i][j]+solve(i+1,j,grid);       int b=0,c=0;       if(i>1)       {           b=grid[i][j]+solve(i-1,j,grid);       }       if(j>1)       {           c=grid[i][j]+solve(i,j-1,grid);       }       int d=grid[i][j]+solve(i,j+1,grid);       return t[i][j]=min({a,b,c,d});}   int minimumCostPath(vector<vector<int>>& grid)    {       memset(t,-1,sizeof(t));       return solve(0,0,grid);   }
+3
roboto7o32oo32 weeks ago
Clean C++ Solution ✨ ✨ (Using Dijkstra's Algorithm and Priority Queue)
 
class Solution
{
    public:
    
    bool isValidPos(pair<int,int> pos, int n){
        int x = pos.first;
        int y = pos.second;
        
        if(x>=0 and x<n and y>=0 and y<n){
            return true;
        }
        return false;
    }
    
    int minimumCostPath(vector<vector<int>>& grid) 
    {
        int n = grid.size();
        
        priority_queue<pair<int,pair<int,int>>, vector<pair<int,pair<int,int>>>, greater<pair<int,pair<int,int>>>> pq;
        
        vector<vector<int>> distance(n, vector<int>(n, INT_MAX));
        
        vector<pair<int,int>> moves{{1,0}, {0,1}, {-1,0}, {0,-1}};
        
        pq.push({grid[0][0], {0,0}});
        distance[0][0] = grid[0][0];
        
        while(not pq.empty()){
            pair<int,pair<int,int>> curr = pq.top();
            pq.pop();
            
            int dist = curr.first;
            pair<int,int> pos = curr.second;
            
            int x = pos.first;
            int y = pos.second;
            
            for(pair<int,int> move : moves){
                int nx = x + move.first;
                int ny = y + move.second;
                
                if(isValidPos({nx,ny}, n) and distance[nx][ny] > dist + grid[nx][ny]){
                    distance[nx][ny] = dist + grid[nx][ny];
                    pq.push({distance[nx][ny], {nx,ny}});
                }
            }
        }
        
        return distance[n-1][n-1];
    }
};
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested 
                                    against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code.
                                    On submission, your code is tested against multiple test cases consisting of all
                                        possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as
                                        the final solution code.
You can view the solutions submitted by other users from the submission tab.
Make sure you are not using ad-blockers.
Disable browser extensions.
We recommend using latest version of your browser for best experience.
Avoid using static/global variables in coding problems as your code is tested 
                                against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases in coding problems does not guarantee the 
                                correctness of code. On submission, your code is tested against multiple test cases
                                    consisting of all possible corner cases and stress constraints.