-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathDjikstra.cpp
70 lines (64 loc) · 1.44 KB
/
Djikstra.cpp
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
//MIN HEAP
vector< list< pair<int, int> > >adj;
void edge(int u, int v, int w)
{
adj[u].push_back({w,v});
// adj[v].push_back(w,u);
}
int dj(int src, int dest, int n)
{
vector< int >dist(n+1,99999999);
vector< bool >vis(n+1,0);
priority_queue< pair<int,int> , vector<pair<int,int> >, greater< pair<int,int> > >pq;
dist[src]=0;
pq.push({0,src});
int count=1;
while(!pq.empty())
{
int ver=pq.top().second;
int wt=pq.top().first;
pq.pop();
// if(ver==dest) break;
if(vis[ver]) continue;
vis[ver]=1;
for(auto x:adj[ver])
{
if((wt+x.first)< dist[x.second])
{
dist[x.second]=wt+x.first;
pq.push({dist[x.second],x.second});
}
}
}
return dist[dest];
}
//Adjacency Matrix
void djikstra(int **cost,int source, int n)
{
vector<bool>visited(n+1,false);
vector<int>dist(n+1,999999);
dist[source]=0;
for(int a=1;a<=n;a++)
{
int max=999999;
for(int b=1;b<=n;b++)
{
if(!visited[b] &&dist[b]<max)
{
max=dist[b];
source=b;
}
}
visited[source]=true;
for(int a=1;a<=n;a++)
{
if(dist[a]>(cost[source][a]+dist[source]) && !visited[a])
{
dist[a]=cost[source][a]+dist[source];
}
}
}
for(int a=1;a<=n;a++)
cout<<a<<"\t"<<dist[a]<<endl;
return ;
}