teacher
Sign in

Shortest Paths

Dijkstra with lazy deletion for non-negative weights, 0-1 BFS for weights 0 and 1, Bellman-Ford for negative edges and Floyd-Warshall for all pairs on small graphs.

55 minCF 1500–20004 interactive11 problems

The problem

Each edge now has a weight (a length, a cost, a time). The length of a path is the sum of its edge weights. The shortest path problem asks for the smallest total from a source node to every other node.

Plain BFS counts edges, so it fails here: a path with 2 heavy edges can be longer than a path with 5 light ones.

Which tool to use depends on the weights:

SituationToolTime
All weights equalBFSO(n+m)O(n + m)
Weights only 0 or 10-1 BFSO(n+m)O(n + m)
Weights ≥0\ge 0DijkstraO((n+m)log⁡n)O((n + m) \log n)
Negative weights possibleBellman-FordO(n⋅m)O(n \cdot m)
All pairs, nn up to a few hundredFloyd-WarshallO(n3)O(n^3)
1 of 9