Skip to content

Commit

Permalink
Create PathWithMinimumEffort.cpp
Browse files Browse the repository at this point in the history
  • Loading branch information
kshitiz11101 authored Jun 26, 2024
1 parent 502ed84 commit 95a6344
Showing 1 changed file with 42 additions and 0 deletions.
42 changes: 42 additions & 0 deletions Graphs/PathWithMinimumEffort.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
class Solution {
public:
int minimumEffortPath(vector<vector<int>>& heights) {

// {diff,{row,col}}
priority_queue<pair<int,pair<int,int>>,
vector<pair<int,pair<int,int>>>,
greater<pair<int,pair<int,int>>>>pq;
int n=heights.size();
int m=heights[0].size();
vector<vector<int>>dist(n,vector<int>(m,1e9));
dist[0][0]=0;
pq.push({0,{0,0}});
int dr[]={-1,0,1,0};
int dc[]={0,1,0,-1};
while(!pq.empty()){
auto it=pq.top();
pq.pop();
int diff=it.first;
int row=it.second.first;
int col=it.second.second;
if(row==n-1 && col==m-1){
return diff;
}
// {row-1,col} ,{row,col+1},{row+1,col},{row,col-1}
for(int i=0;i<4;i++){
int nrow=row+dr[i];
int ncol=col+dc[i];
if(nrow>=0 && ncol>=0 && nrow<n && ncol<m ){
int newEffort=max(abs(heights[row][col]-heights[nrow][ncol]),diff);
if(newEffort<dist[nrow][ncol]){
dist[nrow][ncol]=newEffort;
pq.push({newEffort,{nrow,ncol}});
}

}
}
}

return 0;
}
};

0 comments on commit 95a6344

Please sign in to comment.