-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfloydwarshall.cpp
More file actions
83 lines (70 loc) · 2.08 KB
/
floydwarshall.cpp
File metadata and controls
83 lines (70 loc) · 2.08 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
#include <iostream>
using namespace std;
class Graph {
int **dist;
int vertices;
public:
Graph(int v) {
vertices = v;
dist = new int*[vertices];
for (int i = 0; i < vertices; i++) {
dist[i] = new int[vertices];
for (int j = 0; j < vertices; j++) {
if (i == j)
dist[i][j] = 0;
else
dist[i][j] = 1e9; // Large value representing infinity
}
}
}
void addEdge(int u, int v, int weight) {
dist[u][v] = weight;
}
void floydWarshall() {
for (int k = 0; k < vertices; k++) {
for (int i = 0; i < vertices; i++) {
for (int j = 0; j < vertices; j++) {
if (dist[i][k] != 1e9 && dist[k][j] != 1e9 && dist[i][k] + dist[k][j] < dist[i][j]) {
dist[i][j] = dist[i][k] + dist[k][j];
}
}
}
}
}
void printDistances() {
cout << "Shortest distances between every pair of vertices:\n";
for (int i = 0; i < vertices; i++) {
for (int j = 0; j < vertices; j++) {
if (dist[i][j] == 1e9)
cout << "INF ";
else
cout << dist[i][j] << " ";
}
cout << "\n";
}
}
~Graph() {
for (int i = 0; i < vertices; i++) {
delete[] dist[i];
}
delete[] dist;
}
};
int main() {
int v, e;
cout << "Enter number of vertices: ";
cin >> v;
Graph g(v);
cout << "Enter number of edges: ";
cin >> e;
cout << "Enter edges (source destination weight):\n";
for (int i = 0; i < e; i++) {
int u, v, w;
cin >> u >> v >> w;
g.addEdge(u, v, w);
}
g.floydWarshall();
g.printDistances();
return 0;
}
//This program initializes a graph with user input, runs the Floyd-Warshall algorithm to compute shortest paths between all pairs of vertices, and prints the result. Let me know if you need any modifications!