TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
floyd_warshall.cpp
1#include <climits>
2#include <cstddef>
3#include <iostream>
4#include <vector>
5
6using std::cin;
7using std::cout;
8using std::endl;
9
10// Wrapper class for storing a graph
11class Graph {
12 public:
13 int vertexNum;
14 int **edges;
15
16 // Constructs a graph with V vertices and E edges
17 Graph(int V) {
18 this->vertexNum = V;
19 this->edges = new int *[V];
20 for (int i = 0; i < V; i++) {
21 this->edges[i] = new int[V];
22 for (int j = 0; j < V; j++) this->edges[i][j] = INT_MAX;
23 this->edges[i][i] = 0;
24 }
25 }
26
27 ~Graph() {
28 for (int i = 0; i < vertexNum; i++) {
29 delete[] edges[i];
30 }
31 delete[] edges;
32 }
33
34 // Adds the given edge to the graph
35 void addEdge(int src, int dst, int weight) {
36 this->edges[src][dst] = weight;
37 }
38};
39
40// Utility function to print distances
41void print(const std::vector<int>& dist, int V) {
42 cout << "\nThe Distance matrix for Floyd - Warshall" << endl;
43 for (int i = 0; i < V; i++) {
44 for (int j = 0; j < V; j++) {
45 if (dist[i * V + j] != INT_MAX)
46 cout << dist[i * V + j] << "\t";
47 else
48 cout << "INF"
49 << "\t";
50 }
51 cout << endl;
52 }
53}
54
55// The main function that finds the shortest path from a vertex
56// to all other vertices using Floyd-Warshall Algorithm.
57void FloydWarshall(Graph graph) {
58 std::size_t V = graph.vertexNum;
59 std::vector<std::vector<int> > dist(V, std::vector<int>(V));
60
61 // Initialise distance array
62 for (int i = 0; i < V; i++)
63 for (int j = 0; j < V; j++) dist[i][j] = graph.edges[i][j];
64
65 // Calculate distances
66 for (int k = 0; k < V; k++)
67 // Choose an intermediate vertex
68
69 for (int i = 0; i < V; i++)
70 // Choose a source vertex for given intermediate
71
72 for (int j = 0; j < V; j++)
73 // Choose a destination vertex for above source vertex
74
75 if (dist[i][k] != INT_MAX && dist[k][j] != INT_MAX &&
76 dist[i][k] + dist[k][j] < dist[i][j])
77 // If the distance through intermediate vertex is less than
78 // direct edge then update value in distance array
79 dist[i][j] = dist[i][k] + dist[k][j];
80
81 // Convert 2d array to 1d array for print
82 std::vector<int> dist1d(V * V);
83 for (int i = 0; i < V; i++)
84 for (int j = 0; j < V; j++) dist1d[i * V + j] = dist[i][j];
85
86 print(dist1d, V);
87}
88
89// Driver Function
90int main() {
91 int V, E;
92 int src, dst, weight;
93 cout << "Enter number of vertices: ";
94 cin >> V;
95 cout << "Enter number of edges: ";
96 cin >> E;
97 Graph G(V);
98 for (int i = 0; i < E; i++) {
99 cout << "\nEdge " << i + 1 << "\nEnter source: ";
100 cin >> src;
101 cout << "Enter destination: ";
102 cin >> dst;
103 cout << "Enter weight: ";
104 cin >> weight;
105 G.addEdge(src, dst, weight);
106 }
107 FloydWarshall(G);
108
109 return 0;
110}
double k(double x)
Another test function.
int main()
Main function.
#define endl
Graph Algorithms.