-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSource.cpp
More file actions
145 lines (115 loc) · 2.49 KB
/
Source.cpp
File metadata and controls
145 lines (115 loc) · 2.49 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
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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
#include<stdio.h>
#include<conio.h>
#include <iostream>
#include <fstream>
#define INFINITY 9999
#define MAX 10
using namespace std;
class graph {
public:
int distance[MAX];
int pred[MAX];
int roud[MAX];
};
void dijkstra(int G[MAX][MAX], int n, int startnode);
int main()
{
ifstream f_in;
f_in.open("map.txt");
int G[MAX][MAX], i, j, n, u;
printf("Enter no. of vertices:");
// int G[MAX][MAX];
f_in >> n;
printf("\nEnter the adjacency matrix:\n");
for (i = 0; i < n; i++)
for (j = 0; j < n; j++)
f_in >> G[i][j];
printf("\nEnter the starting node:");
f_in >> u;
dijkstra(G, n, u);
return 0;
}
void dijkstra(int G[MAX][MAX], int n, int startnode)
{
graph g1;
int cost[MAX][MAX];
int visited[MAX], count, mindistance, nextnode, i, j;
//int roud[MAX];
for (i = 0; i < n; i++)
for (j = 0; j < n; j++)
if (G[i][j] == 0)
cost[i][j] = INFINITY;
else
cost[i][j] = G[i][j];
for (i = 0; i < n; i++)
{
g1.distance[i] = cost[startnode][i];
g1.pred[i] = startnode;
visited[i] = 0;
g1.roud[i] = 1;
}
g1.distance[startnode] = 0;
visited[startnode] = 1;
count = 1;
while (count < n - 1)
{
mindistance = INFINITY;
//nextnode äຠâåðøèíó íà ì³í³ìàëüí³é â³äñòàí³
for (i = 0; i < n; i++)
if (g1.distance[i] < mindistance && !visited[i])
{
mindistance = g1.distance[i];
nextnode = i;
}
//ïåðåâ³ðèòè, ÷è ³ñíóº êðàùèé øëÿõ ÷åðåç nextnode
visited[nextnode] = 1;
for (i = 0; i < n; i++){
if (!visited[i])
if (mindistance + cost[nextnode][i] < g1.distance[i])
{
g1.distance[i] = mindistance + cost[nextnode][i];
g1.pred[i] = nextnode;
}
}
count++;
}
for (i = 4; i < n; i++)
if (i != startnode)
{
j = i;
printf("%d", i);
do
{
j = g1.pred[j];
printf("<-%d", j);
g1.roud[i]++;
} while (j != startnode);
}
int temp = 0;
int index[MAX];
int tmp =900 ;
for (i = 0; i < n; i++) {
if (g1.roud[i] >= temp) {
temp = g1.roud[i];
}
}
for (i = 0; i < n; i++) {
if (g1.roud[i] == temp) {
index[i] = i;
}
else
index[i] = 0;
}
for (i = 0; i < n; i++) {
if (index[i] != 0)
{
if (g1.distance[i] < tmp)
{
tmp = g1.distance[i];
temp = i;
}
}
}
cout << "\nDintances " << tmp << "country no " << temp << endl;
//cout << "Dintance min " << distance[i] << "country" << temp << endl;
}