-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGraph_Dijkstra_1.cpp
76 lines (72 loc) · 1.62 KB
/
Graph_Dijkstra_1.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
71
72
73
74
75
76
#include <bits/stdc++.h>
using namespace std;
#define V 9
int graph[V][V] = { { 0, 4, 0, 0, 0, 0, 0, 8, 0 },
{ 4, 0, 8, 0, 0, 0, 0, 11, 0 },
{ 0, 8, 0, 7, 0, 4, 0, 0, 2 },
{ 0, 0, 7, 0, 9, 14, 0, 0, 0 },
{ 0, 0, 0, 9, 0, 10, 0, 0, 0 },
{ 0, 0, 4, 14, 10, 0, 2, 0, 0 },
{ 0, 0, 0, 0, 0, 2, 0, 1, 6 },
{ 8, 11, 0, 0, 0, 0, 1, 0, 7 },
{ 0, 0, 2, 0, 0, 0, 6, 7, 0 } };
int front[V], d[V];
bool final[V];
void Dijkstra(int s, int t)
{
int u,v, min;
front[s] = -1;
d[s] = 0;
final[s] = true;
for(int i=0; i < V; i++)
{
front[i] = s;
final[i] = false;
if(graph[s][i])
{
d[i] = graph[s][i];
} else d[i] = INT_MAX;
}
final[s] = true;
while(!final[t])
{
min = INT_MAX;
for(int i=0; i < V; i++)
{
if(!final[i] && d[i] < min)
{
u = i;
min = d[i];
}
}
final[u] = true;
if(!final[t])
{
for(int i=0; i < V; i++)
{
if(!final[i] && d[u] + graph[u][i] < d[i])
{
d[i] = d[u] + graph[u][i];
front[i] = u;
}
}
}
}
}
void Result(int s, int t)
{
int i = front[t];
while(i != s)
{
cout << i << " ";
i = front[i];
}
cout << endl << d[t] << endl;
}
int main()
{
int s, t;
cin >> s >> t;
Dijkstra(s, t);
Result(s, t);
}