forked from rustednickle/competitive-programming-library
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdijkstras.cpp
More file actions
51 lines (43 loc) · 886 Bytes
/
Copy pathdijkstras.cpp
File metadata and controls
51 lines (43 loc) · 886 Bytes
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
#include<bits/stdc++.h>
#define fori(i,n) for(int i=0;i<n;i++)
using namespace std;
#ifndef fori
#define fori(i,n) for(int i=0;i<n;i++)
#endif
vector<int> dijkstrasAlgo(vector<vector<int> >g, int start)
{
int n = g.size();
vector<int> dist(n,INT_MAX);
vector<int> Q(n); // Q->unvisited nodes
fori(i,n)Q[i]=i;
dist[start] = 0;
int u=start;
while(!Q.empty())
{
int min = 0;
fori(j,Q.size())
if(dist[Q[j]]<dist[Q[min]]) min = j;
u = Q[min];
Q.erase(Q.begin()+min);
fori(i,n)
if(u!=i && g[u][i]!=-1){
int alt = dist[u]+g[u][i];
if(alt<dist[i]) dist[i]= alt;
}
}
return dist;
}
int main()
{
int input_n;
cout << "Enter value of n: "<< endl;
cin>>input_n;
vector<vector<int> >g(input_n, vector<int>(input_n));
fori(i,input_n){
fori(j,input_n){
cin>>g[i][j];
}
}
vector<int> t = dijkstrasAlgo(g,0);
fori(i,input_n)cout<<t[i]<<" ";
}