-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathDijkstraShortestPath.cpp
116 lines (110 loc) · 2.83 KB
/
DijkstraShortestPath.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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
#include<bits/stdc++.h>
using namespace std;
void showpath(int path[],int i)
{
if (path[i]==-1)
return;
showpath(path,path[i]);
cout<<char('A'+i)<<"\t";
}
int mindist(int dist[],char traversed[],int n)
{
int min=9999;
int min_pos;
for(int i=0;i<n;i++){
if (traversed[i] == '\0' && dist[i] <= min)
{
min = dist[i];
min_pos = i;
}
}
return min_pos;
}
void printDistance(int matrix[][100], int n)
{
char vertice1 = 'A';
char vertice2 = 'A';
for (int i = -1; i < n; i++)
{
for (int j = -1; j < n; j++)
{
if (i == -1 && j == -1)
{
cout << "Dist "<< "\t";
}
else if (i == -1 && j != -1)
{
cout << vertice1++ << "\t";
}
else if (j == -1 && i != -1)
{
cout << vertice2++ << "\t";
}
else
cout << matrix[i][j] << "\t";
}
cout << endl;
}
}
void printSolution(int dist[],int n,int path[])
{
cout<<"Vertex \t\t Distance from Source\t\tPath"<<endl;
for (int i = 0; i < n; i++){
cout<<endl<<'A'<<"->"<<char('A'+i)<<"\t\t"<<dist[i]<<"\t\t\t\t"<<'A'<<"\t";
showpath(path,i);
}
}
void dijktras(int weight[][100],int n,int source)
{
int path[n];
int dist[n];
char traversed[n];
for (int i=0;i<n;i++)
{
if (i!=source)
{
dist[i]=9999;
}
else
{
dist[i]=0;
path[i]=-1;
}
traversed[i]='\0';
}
int min=9999;
int min_pos;
for (int i=0;i<n-1;i++)
{
int min_pos=mindist(dist,traversed,n);
traversed[min_pos] = char('A' + i);
for (int j=0;j<n;j++)
{
if(traversed[j]=='\0'&& weight[min_pos][j] && dist[min_pos]!=9999 && dist[min_pos]+weight[min_pos][j]<dist[j])
{
dist[j]=dist[min_pos]+weight[min_pos][j];
path[j]=min_pos;
}
}
}
printSolution(dist,n,path);
}
int main()
{
int n;
cout << "Enter number of vertices in the graph:" << endl;
cin >> n;
int weight[100][100];
cout << "Enter weights of the paths connecting each vertex(Enter 9999 for the pair of vertices with no path):" << endl;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
cout << "Enter weight of path between " << char('A' + i) << " to " << char('A' + j) << endl;
cin >> weight[i][j];
}
}
cout << "The data showing shortest paths connecting source and rest of the vertices:" << endl;
printDistance(weight, n);
dijktras(weight,n,0);
}