Floyd Warshall Algorithm

The Floyd-Warshall algorithm is a dynamic programming algorithm used to find the shortest path between all pairs of vertices in a weighted directed graph (with or without negative edge weights). It is based on the concept of dynamic programming and uses a matrix to store the intermediate shortest path distances between vertices.


Here is a step-by-step explanation of the Floyd-Warshall algorithm:


1. Create a matrix `dist` of size V x V, where V is the number of vertices in the graph. Initialize `dist[i][j]` to positive infinity for all i ≠ j, and set `dist[i][i]` to 0 for all i.

2. For each edge (u, v) in the graph, set `dist[u][v]` to the weight of the edge.

3. Perform the following steps for each vertex k from 1 to V: a. For each pair of vertices i and j, check if the distance from i to j via vertex k (`dist[i][k] + dist[k][j]`) is shorter than the current distance `dist[i][j]`. If it is, update `dist[i][j]` with the new shorter distance.

4. After the algorithm completes, the `dist` matrix will contain the shortest path distances between all pairs of vertices.


Here is a pseudocode representation of the Floyd-Warshall algorithm:

FloydWarshall(graph):
    V = number of vertices in the graph
    dist = a matrix of size V x V

// Step 1
Initialize dist[i][j] to positive infinity for all i ≠ j
Set dist[i][i] to 0 for all i

// Step 2
for each edge (u, v) in the graph:
    dist[u][v] = weight of edge (u, v)

// Step 3
for k from 1 to V:
    for i from 1 to V:
        for j from 1 to V:
            if dist[i][k] + dist[k][j] < dist[i][j]:
                dist[i][j] = dist[i][k] + dist[k][j]

return dist

The time complexity of the Floyd-Warshall algorithm is O(V^3), where V is the number of vertices in the graph. This is because the algorithm iterates through all vertices and considers all possible pairs of vertices as intermediate points. The space complexity is O(V^2) to store the `dist` matrix.

The Floyd-Warshall algorithm is particularly useful when we need to find the shortest path between all pairs of vertices in a dense graph or when the graph has negative edge weights. However, it may not be as efficient as other algorithms like Dijkstra's algorithm or Bellman-Ford algorithm for finding the shortest path between two specific vertices.



About the Author



Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.

We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc





 PreviousNext