-
Notifications
You must be signed in to change notification settings - Fork 77
/
Copy pathFloyyd_Warshall.cpp
67 lines (55 loc) · 1.53 KB
/
Floyyd_Warshall.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
#include <iostream>
#include <vector>
#include <climits>
using namespace std;
const int INF = INT_MAX;
class Graph {
public:
int V; // Number of vertices
vector<vector<int>> dist;
Graph(int vertices) {
V = vertices;
dist.resize(V, vector<int>(V, INF));
// Initialize diagonal elements to 0
for (int i = 0; i < V; i++) {
dist[i][i] = 0;
}
}
void addEdge(int u, int v, int w) {
dist[u][v] = w;
}
void floydWarshall() {
for (int k = 0; k < V; k++) {
for (int i = 0; i < V; i++) {
for (int j = 0; j < V; j++) {
if (dist[i][k] != INF && dist[k][j] != INF && dist[i][k] + dist[k][j] < dist[i][j]) {
dist[i][j] = dist[i][k] + dist[k][j];
}
}
}
}
cout << "Shortest distances between all pairs of vertices:\n";
for (int i = 0; i < V; i++) {
for (int j = 0; j < V; j++) {
if (dist[i][j] == INF) {
cout << "INF ";
} else {
cout << dist[i][j] << " ";
}
}
cout << "\n";
}
}
};
int main() {
int V, E; // Number of vertices and edges
cin >> V >> E;
Graph g(V);
for (int i = 0; i < E; i++) {
int u, v, w;
cin >> u >> v >> w;
g.addEdge(u, v, w);
}
g.floydWarshall();
return 0;
}