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
abhishekpanwar6972 days ago
 int minimumCostPath(vector<vector<int>>& a)    {      int n=a.size(),m=a[0].size();      vector<vector<int>>dist(n+1,vector<int>(m+1,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]=a[0][0];      pq.push({dist[0][0],{0,0}});      int x[4]={1,-1,0,0};      int y[4]={0,0,1,-1};      while(!pq.empty())      {          auto t=pq.top();          pq.pop();          int w=t.first;          int i=t.second.first;          int j=t.second.second;          if(i==n-1&&j==m-1)          break;          for(int k=0;k<4;k++)          {              int u=i+x[k];              int v=j+y[k];              if(u>=0&&u<n&&v>=0&&v<m&&dist[u][v]>dist[i][j]+a[u][v])              {                  dist[u][v]=dist[i][j]+a[u][v];                  pq.push({dist[u][v],{u,v}});              }          }      }      return dist[n-1][m-1];   }
0
dusankovacevic2 weeks ago
For some reason it gave me this code when looking up greedy tasks.
0
bhaskarmaheshwari83 weeks ago
//  https://www.youtube.com/watch?v=jbhuqIASjoM
bool isSafe(int row,int col,int n){    if(row<0||col<0||row>n-1||col>n-1)    return 0;    return 1;}   int minimumCostPath(vector<vector<int>>& grid)    {       // Code here       int n=grid.size();             priority_queue<pair<int,pair<int,int>>, vector<pair<int,pair<int,int>>>, greater<pair<int,pair<int,int>>> > q;       vector<vector<int>> dist(n,vector<int>(n,INT_MAX));       q.push({grid[0][0],{0,0}});              dist[0][0]=grid[0][0];       int dx[]={-1,1,0,0};       int dy[]={0,0,-1,1};              while(!q.empty())       {           int distance=q.top().first;           int row=q.top().second.first;           int col=q.top().second.second;           q.pop();                      for(int i=0;i<4;i++)           {               if(isSafe(row+dx[i],col+dy[i],n))               {                   if(dist[row+dx[i]][col+dy[i]]>distance+grid[row+dx[i]][col+dy[i]])                   {                       dist[row+dx[i]][col+dy[i]]=distance+grid[row+dx[i]][col+dy[i]];                       q.push({ dist[row+dx[i]][col+dy[i]],{row+dx[i],col+dy[i]}});                   }               }           }                             }       return dist[n-1][n-1];              
0
akashmr10961 month ago
//Function to return the minimum cost to react at bottom
	//right cell from top left cell.
    public int minimumCostPath(int[][] grid)
    {
        // Code here
        int n = grid.length;
        int dist[][] = new int[n][n];
        for(int i=0; i<n; i++)
            Arrays.fill(dist[i], Integer.MAX_VALUE);
        
        boolean visited[][] = new boolean[n][n];
        PriorityQueue<Node> q = new PriorityQueue<>();
        dist[0][0] = grid[0][0];
        q.offer(new Node(0, 0, dist[0][0]));
        while(!q.isEmpty()) {
            Node next = q.poll();
            //System.out.println(String.format("i: %d j: %d dist: %d", next.i, next.j, next.dist));
            if (next.i == n-1 && next.j == n-1) {
                return next.dist;
            } else {
                bfs(next, n, visited, dist, grid, q);
            }
        }
        return dist[n-1][n-1];
    }
    
    private void bfs(Node next, int n, boolean visited[][], int dist[][], int grid[][], PriorityQueue<Node> q) {
        int i = next.i;
        int j = next.j;
        if (visited[i][j]) {
            return;
        }
        
        visited[i][j] = true;
        
        if (j > 0) {
            dist[i][j-1] = Math.min(dist[i][j-1], next.dist+grid[i][j-1]);
            q.offer(new Node(i, j-1, dist[i][j-1]));
        }
        
        if (j < n-1) {
            dist[i][j+1] = Math.min(dist[i][j+1], next.dist+grid[i][j+1]);
            q.offer(new Node(i, j+1, dist[i][j+1]));
        }
        
        if (i > 0) {
            dist[i-1][j] = Math.min(dist[i-1][j], next.dist+grid[i-1][j]);
            q.offer(new Node(i-1, j, dist[i-1][j]));
        }
        
        if (i < n-1) {
            dist[i+1][j] = Math.min(dist[i+1][j], next.dist+grid[i+1][j]);
            q.offer(new Node(i+1, j, dist[i+1][j]));
        }
    }
    
    static class Node implements Comparable<Node> {
        int i;
        int j;
        int dist;
        
        public Node(int i, int j, int dist) {
            this.i = i;
            this.j = j;
            this.dist = dist;
        }
        
        @Override
        public int compareTo(Node n) {
            return this.dist-n.dist;
        }
    }
+3
vinamrajha2 months ago
bool isvalid(int i, int j, int row, int col){
    if(i<0 || j<0 || i>=row || j>=col)return false;
    return true;
}
   int minimumCostPath(vector<vector<int>>& grid) 
   {
       // Code here
       int row = grid.size(), col = grid[0].size(), 		    fcost =0;
       vector<vector<int>> dist(row, vector<int>(col, INT_MAX));
       dist[0][0] = grid[0][0];
       priority_queue< pair<int,pair<int,int>>, vector<pair<int,pair<int,int>>>, greater<pair<int,pair<int,int>>>> pq;
       int dx[4] = {1,-1,0,0};
       int dy[4] = {0,0,1,-1};
       pq.push({dist[0][0],{0,0}});
       while(!pq.empty()){
           auto p = pq.top();
           pq.pop();
           int cost = p.first;
           auto q = p.second;
           int i = q.first;
           int j = q.second;
           fcost += cost;
           if(i==row-1 && j==col-1) break;
           for(int k =0; k<4; ++k){
               int xdx = i + dx[k];
               int ydy = j + dy[k];
               if(isvalid(xdx, ydy, row, col)){
                   if(dist[xdx][ydy]>=dist[i][j]+grid[xdx][ydy]){
                       dist[xdx][ydy] = dist[i][j] + grid[xdx][ydy];
                       pq.push({dist[xdx][ydy],{xdx, ydy}});
                   }
               }
           }
       }
       return dist[row-1][col-1];
   }
+1
madhukartemba2 months ago
JAVA SOLUTION USING PRIORITY QUEUE:
class Pair implements Comparable<Pair>
{
    int x, y, cost;
    
    Pair(int x, int y, int cost)
    {
        this.x = x;
        this.y = y;
        this.cost = cost;
    }
    
    
    public int compareTo(Pair p)
    {
        return cost - p.cost;
    }
}


class Solution
{
    
    private boolean inLimits(int x, int y, int n)
    {
        return (x>=0 && y>=0 && x<n && y<n);
    }
    
    //Function to return the minimum cost to react at bottom
	//right cell from top left cell.
    public int minimumCostPath(int[][] grid)
    {
        int n = grid.length;
        
        PriorityQueue<Pair> pq = new PriorityQueue<>();
        
        pq.add(new Pair(0, 0, grid[0][0]));
        
        boolean visited[][] = new boolean[n][n];
        
        int dx[] = {1, 0, -1, 0};
        int dy[] = {0, 1, 0, -1};
        
        while(!pq.isEmpty())
        {
            Pair p = pq.poll();
            
            visited[p.x][p.y] = true;
            
            for(int i=0; i<4; i++)
            {
                int x = p.x + dx[i];
                int y = p.y + dy[i];
                
                if(inLimits(x, y, n) && visited[x][y] == false)
                {
                    if(x==n-1 && y==n-1) return p.cost + grid[x][y];
                    visited[x][y] = true;
                    
                    pq.add(new Pair(x, y, p.cost + grid[x][y]));
                    
                }
            }
        }
        
        return -1;
        
    }
}
0
avenvy2 months ago
Python implementation using Dijkstra's Algo  using Heap  for 2D array(submitted solution) 
import heapq
class Solution:
	def minimumCostPath(self, grid):
		#Code here
		m=len(grid)
		n=len(grid[0])
	    i=0 
	    j=0
	    dist=[[float("inf")]*n for i in range(m)]
	    dist[i][j]=grid[i][j]
	    pq=[]
	    dx = [0, 0, 1, -1]
        dy = [1, -1, 0, 0]
        heapq.heappush(pq,(grid[0][0],(0,0)))
        while pq:
            wt,nei=heapq.heappop(pq)
            u=nei[0]
            v=nei[1]
            for k in range(4):
                nu=u+dx[k]
                nv=v+dy[k]
                if 0<=nu<n and 0<=nv<m and wt+grid[nu][nv]<dist[nu][nv]:
                    nwt=wt+grid[nu][nv]
                    dist[nu][nv]=nwt
                    heapq.heappush(pq,(nwt,(nu,nv)))
		return dist[n-1][m-1]
+1
shouryarastogi2 months ago
Can someone tell why its givind TLE after 11 test cases
class Solution{   //Function to return the minimum cost to react at bottom//right cell from top left cell.    static class Node implements Comparable<Node>{       String key;       int distance;
       public Node(String key, int distance) {           this.key = key;           this.distance = distance;       }              @Override       public int compareTo(Node n){           return this.distance-n.distance;       }              @Override       public boolean equals(Object o){           Node n=(Node) o;           return n.key.equals(this.key);       }              @Override       public int hashCode(){           return Objects.hash(key);       }          }      public static int minimumCostPath(int[][] grid)   {       int rowMax=grid.length;       int colMax=grid[0].length;
       Map<String, List<Node>> connectionMap=new HashMap<>();       Map<String,Integer> distanceMap=new HashMap<>();       PriorityQueue<Node> pq=new PriorityQueue<>();       for(int i=0;i<rowMax;i++){           for(int j=0;j<colMax;j++){               String key=i+"_"+j;               if(i==0&&j==0){                   distanceMap.put(key,0);                   pq.add(new Node(key,0));               }else{                   distanceMap.put(key,100000);                   pq.add(new Node(key,100000));               }               List<Node> connections=new ArrayList<>();               if(i-1>=0){                   connections.add(new Node((i-1)+"_"+j,grid[i-1][j]));               }               if(i+1<rowMax){                   connections.add(new Node((i+1)+"_"+j,grid[i+1][j]));               }               if(j-1>=0){                   connections.add(new Node(i+ "_"+(j-1),grid[i][j-1]));               }               if(j+1<colMax){                   connections.add(new Node(i+"_"+(j+1),grid[i][j+1]));               }               connectionMap.put(key,connections);           }       }        Map<String,String> visited=new HashMap<>();        while (!pq.isEmpty()){           Node top = pq.poll();           if(visited.containsKey(top.key)){               continue;           }           visited.put(top.key,"");           List<Node> connections = connectionMap.get(top.key);           for(Node each: connections){               Integer existingDistance = distanceMap.get(each.key);               Integer newDistance = top.distance + each.distance;               Integer minDistance=Math.min(existingDistance,newDistance);               distanceMap.put(each.key,minDistance);               pq.remove(new Node(each.key,1));               pq.add(new Node(each.key,minDistance));           }       }              return distanceMap.get((rowMax-1)+"_"+(colMax-1)) + grid[0][0];   }}
0
bhaskarmaheshwari83 months ago
Why this question cant be done using backtracking??
 
can anyone tell whats wrong in this as public test cases are passing when i submitting it saying wrong answer??
 
int visited[1005][1005];int dp[1005][1005];Solution(){    memset(visited,0,sizeof(visited));     memset(dp,-1,sizeof(dp));}int helper(vector<vector<int>>& grid,int n,int row,int col){    if(row==n-1&&col==n-1)    return grid[row][col];    if(dp[row][col]!=-1)    return dp[row][col];    int dx[]={0,0,-1,1};    int dy[]={-1,1,0,0};       int ans=INT_MAX/4;   for(int i=0;i<4;i++)   {   if(row+dx[i]>=0&&row+dx[i]<n&&col+dy[i]>=0&&col+dy[i]<n&&!visited[row+dx[i]][col+dy[i]])    {           visited[row][col]=1;            cout<<grid[row][col]<<endl;        ans=min(ans,helper(grid,n,row+dx[i],col+dy[i]));        visited[row][col]=0;           }   }   //cout<<endl;     ans+=grid[row][col];     cout<<endl;   return  dp[row][col]= ans;}   int minimumCostPath(vector<vector<int>>& grid)    {       // Code here       int n=grid.size();       int row=0,col=0;     return helper(grid,n,row,col);                        }
0
apurvpandey173 months ago
 int minimumCostPath(vector<vector<int>>& grid)    {       int n = grid.size();       vector<vector<int>> cost(n,vector<int>(n,INT_MAX-1));       cost[0][0] = grid[0][0];       vector<pair<int,int>> dir = {{0,1},{0,-1},{1,0},{0,-1}};       priority_queue<p, vector<p>, greater<p>> pq;       pq.push({0,{0,0}});       int dist,x,y,px,py,c;       while(! pq.empty()){           x = pq.top().second.first;           y = pq.top().second.second;           pq.pop();           for(auto it:dir){               px = x + it.first;               py = y + it.second;               if(px < n && py < n && px >= 0 && py >= 0)               if(cost[px][py] > cost[x][y] + grid[px][py]){                   cost[px][py] = min(cost[x][y] + grid[px][py], cost[px][py]);                   pq.push({cost[px][py],{px,py}});               }           }       }       return cost[n-1][n-1];   }
 
 
Can anyone tell me what is wrong with this code?
Thanks
 
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.