Floyd–Warshall visualization
All-pairs shortest paths by allowing one more intermediate vertex k at a time.
D[i][j] holds the shortest i→j distance using only intermediate vertices from the first k. Adding vertex k as a possible stop: D[i][j] = min(D[i][j], D[i][k] + D[k][j]).
Works with negative edges. Edge case: a negative value on the diagonal D[i][i] < 0 at the end means vertex i lies on a negative cycle.
Complexity
Time: best O(V³), average O(V³), worst O(V³). Space: O(V²). Difficulty: Advanced.
Pseudocode
procedure floydWarshall(G):
D[i][j] ← w(i, j); D[i][i] ← 0; otherwise ∞
for k in V:
for i in V:
for j in V:
if D[i][k] + D[k][j] < D[i][j]:
D[i][j] ← D[i][k] + D[k][j]
if any D[i][i] < 0: negative cycleMore graphs algorithms
- Breadth-First Search — Explore level by level with a queue — gives shortest paths in unweighted graphs.
- Depth-First Search — Go as deep as possible along each branch before backtracking.
- Dijkstra's Shortest Path — Greedily settle the closest unsettled vertex using a priority queue.
- Bellman–Ford — Relax every edge V−1 times; handles negative weights and detects negative cycles.
- Prim's MST — Grow one tree by always adding the cheapest edge leaving it.
- Kruskal's MST — Sort edges by weight and add each one unless it would create a cycle (union–find).
- Topological Sort (Kahn) — Order a DAG so every edge points forward, by repeatedly removing zero in-degree vertices.
- A* Pathfinding — Best-first search on a grid using cost-so-far g plus a heuristic h towards the goal.