Log In Sign Up
Day

Day 38: Floyd-Warshall Algorithm

/60 Days

Floyd-Warshall Algorithm #

Welcome to Day 38 of our 60 Days of Coding Algorithm Challenge! Today, we’ll explore the Floyd-Warshall algorithm, a powerful algorithm for finding the shortest paths between all pairs of vertices in a weighted graph.

What is the Floyd-Warshall Algorithm? #

The Floyd-Warshall algorithm is an algorithm for finding shortest paths in a weighted graph with positive or negative edge weights (but with no negative cycles). Unlike Dijkstra’s algorithm, which finds the shortest path from a single source to all other vertices, Floyd-Warshall finds the shortest paths between all pairs of vertices.

How Does It Work? #

The algorithm works by iteratively improving an estimate on the shortest path between two vertices, until the estimate is optimal. It does this by considering all possible intermediate vertices between each pair of vertices.

Implementing Floyd-Warshall Algorithm #

Here’s an implementation of the Floyd-Warshall algorithm:

 1def floyd_warshall(graph):
 2    n = len(graph)
 3    dist = [row[:] for row in graph]  # Create a copy of the graph
 4    
 5    # Initialize the distance matrix
 6    for i in range(n): …