-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path36-Shortest Grid Path.cpp
More file actions
77 lines (64 loc) · 1.95 KB
/
36-Shortest Grid Path.cpp
File metadata and controls
77 lines (64 loc) · 1.95 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#include<bits/stdc++.h>
using namespace std;
//dijkshtras
class Node{
public:
int x,y;
int dist;
Node(int x,int y,int dist){
this->x = x;
this->y = y;
this->dist = dist;
}
};
//comparator should return boolean value, indicating whether the element passed as first argument is considered to go before the second in the specific strict weak ordering
class Compare{
public:
bool operator()(Node a,Node b){
return a.dist <= b.dist;
}
};
int shortest_path(vector<vector<int> > grid){
//----------------/////
int m = grid.size();
int n = grid[0].size();
int i = 0;
int j = 0;
vector<vector<int> > dist(m+1,vector<int>(n+1,INT_MAX));
dist[i][j] = grid[0][0];
set<Node,Compare> s;
s.insert(Node(i,j,dist[0][0]));
int dx[] = {0,0,1,-1};
int dy[] = {1,-1,0,0};
while(!s.empty()){
//get the node that is having smallest dist
auto it = s.begin();
int cx = it->x;
int cy = it->y;
int cd = it->dist;
s.erase(it);
//update the neigbours of this node and push them in the set
for(int k=0;k<4;k++){
int nx = cx + dx[k];
int ny = cy + dy[k];
if(nx>=0 and nx<m and ny>=0 and ny<n and dist[nx][ny] > cd + grid[nx][ny]){
//remove the old node from the set
Node temp(nx,ny,dist[nx][ny]);
if(s.find(temp)!=s.end()){
s.erase(s.find(temp));
}
//insert the new node in the set
int nd = grid[nx][ny] + cd;
dist[nx][ny] = nd;
s.insert(Node(nx,ny,nd));
}
}
}
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
cout<<dist[i][j]<<" ";
}
cout<<endl;
}
return dist[m-1][n-1];
}