Does Floyd-Warshall produce correct distances when some edge weights are negative?
answer
- Edges and cycles are different conditions
- The algorithm commits to nothing early
- Every cell stays improvable until the last pass
- Compare with an approach that settles vertices
- Look at the diagonal for the tell
basics
~20 sYes, provided no cycle has negative total weight. The recurrence never finalises a vertex early, so a cheap route found late still improves an entry. With a negative cycle no shortest path exists and the output is meaningless.
solid answer
~50 sFloyd-Warshall is correct on negative edge weights provided no reachable cycle sums to a negative total. The reason is structural: it never declares a vertex finished. Every pair is reconsidered against every waypoint, so an entry written early can be improved much later when a cheaper route through a negative edge finally becomes visible. Contrast that with a greedy settled-set search, which finalises the currently-closest vertex and cannot revisit it. This is the case where an all-pairs run genuinely beats repeating a greedy single-source search from every vertex: the greedy method is not merely slower there, it is wrong. If a negative cycle is reachable, the notion of a shortest path breaks down — you can loop forever and keep getting cheaper — and the matrix values for affected pairs are not distances at all.
go deeper
Learn the one-line rule: negative edges are fine, negative cycles are not. Be able to say why a cycle of negative total weight means no shortest path exists at all, rather than that the algorithm merely fails on it.
Explain the mechanism, not just the rule — nothing is finalised early, so an entry can improve at any later waypoint. Contrast that with an approach that settles the closest vertex and therefore needs non-negative weights to be sound.
Recognise the workload where this is the correctness argument rather than a convenience: all-pairs distances over a cost model with credits. State how you would discharge the no-negative-cycle obligation from the domain rather than hoping a runtime check catches it.
Own the modelling call. Deciding to represent rebates or recovered cost as negative weights buys expressiveness and takes on an invariant the whole system must uphold; decide whether to keep the model non-negative by construction instead, and who owns that argument.
## The condition, stated exactly The requirement is **no negative-weight cycle**, not **no negative-weight edge**. Those are different constraints and conflating them is the single most common error on this topic. A directed graph may be riddled with negative edges and still have perfectly well-defined shortest paths, as long as no closed loop of edges sums to less than zero. Why the distinction matters: shortest paths are only well defined when a cheapest route exists. If some cycle has negative total weight and lies on a route from `i` to `j`, you can go round it again and again, each lap lowering the total. The infimum is minus infinity and no path attains it — so the question "what is the shortest distance" has no answer to compute, in this or any algorithm. ## Why the recurrence tolerates negative edges The algorithm's state is "cheapest cost from `i` to `j` using intermediates only from the permitted set", and it grows that set one vertex at a time. At every step it makes a pure comparison: is the stored value beaten by routing through the newly permitted waypoint? Nothing is ever declared final; every cell stays open to improvement until the last waypoint has been considered. That matters because a negative edge means a longer route can be cheaper. An algorithm that commits — that picks the currently cheapest frontier vertex and treats its distance as settled — depends on the assumption that extending a route never lowers its cost. Drop that assumption and the commitment is unsound: a route that looked expensive early can become the winner once a negative edge downstream is taken into account. Floyd-Warshall makes no such commitment, so it needs no such assumption. The only thing it does assume is the one that justifies its two-way split of the recurrence: that a shortest route using waypoint `k` uses it exactly once, which holds precisely when removing a cycle never increases cost — that is, when no cycle is negative. ## The all-pairs consequence This is where the algorithm earns its place rather than merely being convenient. On a graph with negative edges and no negative cycle, running a greedy single-source search once per vertex does not give you a slower correct answer; it gives you a **wrong** answer, quietly, for the pairs whose best routes take a negative edge late. If you need every pairwise distance on such a graph, your realistic options are one Floyd-Warshall run, or an edge-relaxation single-source method repeated per source, or a reweighting scheme that shifts all weights non-negative using potentials computed by one relaxation run and then applies a fast greedy search per source. Which of those wins is a density question: the reweighting route is asymptotically better on sparse graphs, while the triple loop wins on dense ones with small vertex counts and is far shorter to write and to review. ## Reading the output when the condition is violated Run the algorithm on a graph that does contain a negative cycle and it does not hang or crash — it produces a matrix full of numbers that are not distances. The tell is on the diagonal: a cell `D[i][i]` below zero says a negative-weight cycle is reachable from `i` and returns to it, since a genuine cheapest round trip cannot cost less than nothing. Any pair whose best route can enter that cycle has a meaningless value. This is a check on a precondition, not a feature to lean on; when detecting and characterising such cycles is the actual goal, that is a different algorithm's job, and one worth naming explicitly rather than inferring from a diagonal. Two practical cautions. First, if unreachable pairs are stored as a large sentinel rather than a true infinity, negative edges can drag those sentinels downward and manufacture routes that do not exist — guard the update so a sentinel plus anything stays a sentinel. Second, on an undirected graph a single negative edge is *already* a negative cycle, because you can traverse it back and forth; negative weights therefore only make sense on directed graphs. ## Where negative weights come from in real models They are not exotic. Any cost model with credits produces them: a routing leg that recovers energy on a downhill run, a transfer that earns a rebate, a step that returns a deposit. Whenever the modelled quantity can be gained as well as spent, the graph has negative edges and the question of whether the cycle condition holds becomes an explicit modelling obligation — usually discharged by an argument about the domain, such as "you cannot recover more energy than you spent going up", rather than by a runtime check.
- Why does a negative edge make shortest paths undefined on an undirected graph?Because an undirected edge can be traversed in both directions, a single negative edge is already a cycle of negative total weight — go across and back and you have lowered your cost by twice the weight, repeatable without limit. So negative weights are only meaningful on directed graphs, and a model that produces them must have a direction attached to the saving.
- You need all-pairs distances on a sparse graph that has negative edges. What are your options?Either repeat an edge-relaxation single-source method from every vertex, or reweight: compute vertex potentials with one relaxation run, shift every edge weight non-negative so shortest routes are preserved, then run a fast greedy search per source and subtract the shift back out. The reweighting route is asymptotically better on sparse graphs; the triple loop is simpler and wins when the graph is dense and small.
- If unreachable pairs are stored as a large sentinel number rather than true infinity, what goes wrong?Negative edges can pull those sentinels down, so a pair with no route at all acquires a finite-looking value through an imaginary route built from two non-routes. Guard the relaxation so an update is skipped when either sub-distance is the sentinel, or use a representation whose addition genuinely saturates. Without the guard the bug appears only on graphs that are both disconnected and have negative weights.
A greedy settled-set search is an auction where the first bid accepted is final; Floyd-Warshall keeps every offer open until the last bidder has spoken.
saying these in an interview costs you the question
- Says negative edge weights alone make it incorrect
- Confuses negative edges with negative cycles
- Claims a greedy settled-set search just needs more passes
- Assumes it hangs or errors on a negative cycle
- Applies negative weights to an undirected graph