Day 46: Floyd-Warshall Algorithm
Floyd-Warshall Algorithm#
Welcome to Day 46 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):
7 for j in range(n): …Keep your momentum going
Create a free account to unlock the full lesson, all 60 days, and track your progress as you go.
- Full access to all 60 daily lessons
- Track completion and build a daily streak
- Get interview-ready, one algorithm at a time
Join 2,900+ learners · 4.8/5 average rating