This project provides an academic implementation of the Floyd–Warshall algorithm for solving the All-Pairs Shortest Path (APSP) problem in a weighted directed graph. In addition to computing the shortest distances between all pairs of vertices, the program reconstructs and prints the actual shortest paths between vertices.
The implementation is written in C++ and uses dynamic memory allocation to manage distance and path reconstruction matrices.
The Floyd–Warshall algorithm is a classical dynamic programming technique used to find the shortest paths between all pairs of vertices in a graph. The algorithm iteratively considers each vertex as an intermediate point and updates the shortest known distances accordingly.
- Time Complexity: (O(V^3))
- Space Complexity: (O(V^2))
where (V) denotes the number of vertices in the graph.
To reconstruct the actual shortest paths, an auxiliary matrix called next is used.
next[i][j]stores the next vertex to visit after vertexiwhen following the shortest path fromitoj.- If no path exists between two vertices,
next[i][j]is set to-1.
During the relaxation step of the Floyd–Warshall algorithm, when a shorter path
from vertex i to vertex j through an intermediate vertex k is found,
the following update is applied:
next[i][j] = next[i][k]
This is because the first vertex after i on the shortest path from i to k
is also the first vertex on the shortest path from i to j
when the path passes through k.
Preserving this information guarantees correct and complete reconstruction of the shortest path.
- An integer
Vrepresenting the number of vertices - A
V × Vadjacency matrix
0on the main diagonal (distance from a vertex to itself)- Positive integer → weight of an edge
-1→ no direct edge between vertices
4 0 5 -1 10 -1 0 3 -1 -1 -1 0 1 -1 -1 -1 0
The program outputs:
- The shortest distance matrix
- The reconstructed shortest paths between all vertex pairs
This output indicates that the shortest path from vertex 0 to vertex 3
passes through vertices 1 and 2.
- Infinite distances are represented using a large constant (
INF) - Dynamic memory allocation (
new/delete) is used for matrix management - The implementation correctly handles disconnected vertices
- Paths are printed in a readable sequential format
Compile and execute the program using a C++ compiler such as g++
g++ src/floyd_warshall.cpp -o floyd
./floyd- Network routing and communication systems
- Transportation and traffic analysis
- Graph-based optimization problems
- Educational demonstrations of dynamic programming algorithms
Abtin Fooladkhah