Data Structures and Algorithms • C# examples
Bellman-Ford and Floyd-Warshall Shortest Paths
Choose between single-source negative-edge handling and all-pairs dynamic programming.
Concept
Bellman-Ford relaxes every edge repeatedly and can detect a reachable negative cycle. Floyd-Warshall considers each vertex as an intermediate point to compute all-pairs distances. These algorithms handle negative edges under their stated conditions, unlike Dijkstra, but cost more time.
How to approach it
Bellman-Ford performs up to V - 1 relaxation passes; Floyd-Warshall updates distance[i,j] through each intermediate k.
Complexity
Bellman-Ford O(VE); Floyd-Warshall O(V³) time and O(V²) storage.
C# example
for (int pass = 0; pass < vertexCount - 1; pass++)
foreach (var edge in edges)
if (distance[edge.From] != long.MaxValue)
distance[edge.To] = Math.Min(
distance[edge.To], distance[edge.From] + edge.Weight);
for (int k = 0; k < vertexCount; k++)
for (int i = 0; i < vertexCount; i++)
for (int j = 0; j < vertexCount; j++)
if (allPairs[i, k] != long.MaxValue &&
allPairs[k, j] != long.MaxValue)
allPairs[i, j] = Math.Min(
allPairs[i, j], allPairs[i, k] + allPairs[k, j]);
Expected result or behavior
Bellman-Ford relaxes single-source edges; Floyd-Warshall considers every vertex as an intermediate point.
Practice exercise
Describe the extra Bellman-Ford pass that reveals a reachable negative cycle, then trace one Floyd-Warshall update.
Key takeaway: Shortest-path algorithms are selected by graph size, edge signs, and query pattern.