1. Home
Data Structure

Data Structure Tutorial: Everything You Need to Know

Learn all about data structures with our comprehensive tutorial. Master the fundamentals and advance your skills in organizing and managing data efficiently.

  • 60
  • 14
right-top-arrow

Tutorial Playlist

58 Lessons
31

Floyd Warshall Algorithm: A Step-by-Step Explanation

Updated on 09/08/2024447 Views

Introduction

The Floyd Warshall algorithm or Robert Floyd and Stephen Warshall, is a dynamic programming algorithm, applied to find the shortest paths among all the pairs of vertices in the weighted graph. Contrary to the first one, the Floyd Warshall algorithm is different from Dijkstra's algorithm which is a specialized algorithm to find the smallest path from one vertex to all other vertices, but the Floyd Warshall algorithm estimates the shortest path between all pairs of vertices in a single run. Hence, this function is of the utmost importance for problems that are restricted by the shortest path between all vertices, such as network routing protocols and graph analysis.

Importance of the Algorithm in Graph Theory and Data Structures

Below is the importance of the Floyd Warshall algorithm in graph theory and data structure:

  1. Simplifies Pathfinding in Graphs: Floyd Warshall's algorithm is the one that can calculate the shortest paths between all the vertices in the graph conveniently. In the areas of transportation, computer networks, and social networks, the shortest path between all the nodes is the basis on which the operation is carried out. 
  1. Efficient Handling of Negative Weighted Edges: The Floyd Warshall algorithm is unique from the other path-finding algorithms because it handles the graphs with negative weighted edges and, thus, has the differentness of the solutions to different path-finding problems. 
  1. Transitive Closure: The same algorithm is also useful to solve the transitive closure of a graph; that is, the basic principle in graph theory is vertex reachability. 
  1. Data Structure Agnostic: The Floyd Warshall algorithm is not a product of a certain data structure and therefore it is a very adaptable technology that can be used in many data structures and environments. 

Understanding the Floyd Warshall Algorithm

This algorithm is a dynamic programming algorithm to find the shortest routes between all the vertices of a weighted graph. The algorithm functions utilizing the framework of an n x n matrix. Here, n is the total number of vertices of the graph that stores the shortest distances between all pairs of vertices. 

  1. Initialization: The algorithm starts the matrix with the direct edge weights between vertices if there is an edge between themes, or a large value (such as infinity) if there is no edge. Also, the diagonal elements of the matrix are set to zero because the shortest path from a vertex to itself is always zero. 
  1. Iterative Updates: The algorithm afterwards goes through all the combinations of the vertices (i, j) and for each combination, it examines all the intermediate vertices (k) and checks if the path from vertex i to vertex k, then from vertex k to vertex j is shorter than the current shortest path from vertex i to vertex j.  If it is, the algorithm updates the shortest path. 
  1. Optimal Substructure: The main concept of the Floyd Warshall algorithm is the optimal substructure property which means a global optimal solution can be found by putting together the optimal solutions of the local subproblems. In this case, the algorithm finds the shortest path between any two vertices by looking at all possible intermediate vertices. 

Comparison with Other Pathfinding Algorithms like Dijkstra's Algorithm

Feature

Floyd Warshall Algorithm

Dijkstra's Algorithm

Scope

Finds the shortest paths for all the vertices pairs.

Tries to discover the shortest way from a single starting point to all other vertices.

Edge Weight

Can handle graphs with negative edge weights.

Cannot handle graphs with negative edge weights.

Algorithm Type

Dynamic programming.

Greedy.

Time Complexity

O(V^3), where V denotes number of vertices.

O(V^2) for adjacency matrix representation, O((V+E)logV) for adjacency list representation, where E is the number of edges.

Space Complexity

O(V^2) for storing the distance matrix.

O(V) for the priority queue and O(V^2) for the distance array.

Suitable for

Graphs with many vertices or graphs with negative edge weights are also counted as busy.

To be more specific, sparse graphs or graphs with non-negative edge weights are word graphs.

Warshall Algorithm in Data Structures

The Warshall algorithm, also named the Floyd-Warshall algorithm, is mainly used to discover the transitive closure of a directed graph. Transitive closure is the phrase that is used for the reachability matrix of a graph that reveals the existence of a path from vertex i to vertex j for all the couples of vertices (i, j) in the graph.

However, in the field of data structures, the Warshall algorithm makes use of a two-dimensional matrix to define the graph and to calculate the transitive closure. Every cell (i, j) in the matrix has a boolean value which indicates a direct edge from vertex i  to j.

Applications of the Floyd Warshall Algorithm

Uses of the Floyd Warshall algorithm are given below:

  1. Routing Algorithms in Computer Networks: The principal aspects of which are web crawling, which debugging might also be significant, the construction of a database in computer networks, and a structured layout of the crawlings.
  1. Efficient Pathfinding: The Floyd Warshall algorithm is a tool that is used to calculate the shortest routes between all the router pairs in a network.
  1. Routing Table Updates: Routers, through the calculated shortest paths, change their routing tables and thus, they guarantee that the data packets reach the destination most effectively.
  1. Minimizing Latency: By minimizing the path length of the packets the algorithm causes the latency to be lower and the network to be more efficiently working.

Distance Vector Protocols in Networking

A distance-vector routing protocol in data networks specifies the best route for data packets depending on distance. The process involved in finding the shortest paths is given below:

  1. Dynamic Routing Updates: The distance vector protocols such as RIP are an example of the Floyd Warshall algorithm being used to find the best route in every direction of the destination.
  1. Routing Table Maintenance: Routers make use of the shortest path calculation to adjust their routing tables when there is a need for route updating.
  1. Adapting to Network Changes: Hence, the method aids the routers in dealing with the network changes through the new calculation of the shortest paths.

Finding Transitive Closure in Directed Graphs

Below are steps to find transitive closure in directed graphs:

  1. Defining Transitive Closure: The transitive closure of a graph enlightens whether there is a connection from vertex i to vertex j for all the couples of vertices (i, j) in the graph.
  1. Matrix Representation: The algorithm makes use of a boolean matrix which shows if there is a connection between the vertices, and if true, then there is a path.
  1. Efficient Computation: The algorithm, through the many-times re-computation of the matrix, can perform the transitive closure of the graph and thus, the many-times re-computation of the matrix allows the algorithm to compute the transitive closure of the graph.

Floyd Warshall Algorithm Example with Solution

Imagine a situation where you are the boss of a delivery service that brings packages to different cities in a country. The major objective is to improve the transportation corridors between cities so that travel time and fuel costs are decreased. By using the Floyd Warshall algorithm example, you can find the shortest routes between every city; thus, you get the full system for the routing of your delivery service.

Solution Demonstrating How the Algorithm Solves the Problem

Consider the following graph representing the distances between cities:

A      B      C      D

A      0      3     INF     7

B     INF     0      2      4

C      1     INF     0      2

D     INF    INF    INF     0

  1. Initialization: The distance matrix is to be made and then filled with the direct distances between cities. Cities that are not adjacent are to be marked as "INF".

 A      B      C      D

A      0      3     INF     7

B     INF     0      2      4

C      1     INF     0      2

D     INF    INF    INF     0

  1. Iteration: The shortest paths between the cities have to be discovered by the revision of the distance matrix. For every vertex that lies between city i and city j, check whether the path from city i to city k, then from city k to city j is shorter than the distance from city i to city j. If it is, update the distance matrix.
  • For k = A: A is not accessible, let alone from itself or other cities.
  • For k = B: At present, the lengths from A to C and D via B (A -> B -> C and A -> B -> D) will be revised.
  • For k = C: The distances between A, B, and D through C (A -> C -> B and A -> C -> D) are updated.
  • For k = D: Modify the A to B and B to C (A -> D -> B and A -> D -> C) road trip.

A      B      C      D

A      0      3      3      5

B     INF     0      2      4

C      1      4      0      2

D     INF    INF    INF     0

Final Words

To sum up, the Floyd Warshall algorithm is a very effective instrument for the shortest path calculation between any two vertices in a graph. Its usage in computer networks, routing algorithms, and graph analysis, which are the main fields, makes it a fundamental algorithm. Through the calculation of the shortest paths, the Floyd Warshall algorithm assists in routing system optimization, the minimization of latency in networks, and the solving of complex graph problems. Its capacity to work with graphs that have negative weighted edges and to find the transitive closure of a graph is the reason for its wide use. In a nutshell, the Floyd Warshall algorithm is used for solving important problems in graph theory and data structures. It solves the problems of a wide range of pathfinding and graph analysis.

FAQ

1. What is the Floyd-Warshall algorithm for?

The Floyd-Warshall algorithm is a technique for locating the shortest paths between every vertice pair in a weighted graph; thus, it is very useful when the shortest path between all pairs of vertices needs to be found.

2. What is the Floyd-Warshall algorithm strategy?

The Floyd-Warshall algorithm is a dynamic programming method that is used to update the matrix of the shortest path between all vertices pairs in a graph until the shortest paths are found.

3. What is Dijkstra's algorithm vs. Floyd-Warshall?

It discovers the shortest path from a source vertex to other vertices, while Floyd-Warshall algorithm finds the shortest paths between all pairs of vertices in a graph.

4. What is the difference between Bellman-Ford and Floyd?

The Bellman-Ford algorithm can cope with graphs having negative edge weights and negative cycles, while Floyd-Warshall can manage graphs with negative edges but cannot identify the negative cycles.

5. Is the Floyd-Warshall algorithm greedy?

No, the Floyd-Warshall algorithm is not a greedy one. It starts from the initial path of two vertices and considers all the possible paths between them and updates the shortest path distances in each cycle.

6. Which algorithm is best for the shortest path?

Dijkstra's algorithm is a known algorithm for the shortest path between one vertex and all other vertices, whereas Floyd-Warshall is the best algorithm for the shortest paths between all vertice pairs in a graph.

Mukesh kumar

Mukesh kumar

Working with upGrad as a Senior Engineering Manager with more than 10+ years of experience in Software Development and Product Management.

Get Free Career Counselling
form image
+91
*
By clicking, I accept theT&Cand
Privacy Policy
image
right-top-arrowleft-top-arrow

upGrad Learner Support

Talk to our experts. We’re available 24/7.

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918045604032

Disclaimer

upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enr...