Bellman–Ford visualization
Relax every edge V−1 times; handles negative weights and detects negative cycles.
A shortest path has at most V−1 edges, so V−1 rounds of relaxing every edge are enough to find all distances — even with negative weights.
If a V-th round can still shorten something, a negative cycle is reachable and "shortest path" is undefined (you could loop forever, getting cheaper).
Complexity
Time: best O(E), average O(V·E), worst O(V·E). Space: O(V). Difficulty: Intermediate.
Pseudocode
procedure bellmanFord(G, s):
dist[*] ← ∞; dist[s] ← 0
repeat |V| − 1 times:
for each edge (u, v, w):
if dist[u] + w < dist[v]: dist[v] ← dist[u] + w
if nothing changed: stop early
for each edge (u, v, w):
if dist[u] + w < dist[v]: negative cycle!
return distMore 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.
- 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.
- Floyd–Warshall — All-pairs shortest paths by allowing one more intermediate vertex k at a time.
- A* Pathfinding — Best-first search on a grid using cost-so-far g plus a heuristic h towards the goal.