-
Notifications
You must be signed in to change notification settings - Fork 40
/
Copy pathfloydWarshallAlgo.cpp
53 lines (45 loc) · 1.33 KB
/
floydWarshallAlgo.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
#include <iostream>
#include <vector>
const int INF = 1e9; // A large value representing infinity
void floydWarshall(std::vector<std::vector<int>>& graph) {
int V = graph.size();
//V represents the number of vertices in the graph.
// distance matrix with the graph's adjacency matrix
std::vector<std::vector<int>> dist(V, std::vector<int>(V));
for (int i = 0; i < V; i++) {
for (int j = 0; j < V; j++) {
dist[i][j] = graph[i][j];
}
}
// Applying the Floyd-Warshall algorithm
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];
}
}
}
}
for (int i = 0; i < V; i++) {
for (int j = 0; j < V; j++) {
if (dist[i][j] == INF) {
std::cout << "INF ";
} else {
std::cout << dist[i][j] << " ";
}
}
std::cout << std::endl;
}
}
int main() {
int V = 4;
std::vector<std::vector<int>> graph = {
{0, 3, INF, 5},
{2, 0, INF, 4},
{INF, 1, 0, INF},
{INF, INF, 2, 0}
};
floydWarshall(graph);
return 0;
}