Shortest Paths and Flows as Linear Programs
The graph algorithms of Graph Algorithms are fast and specialized. Linear programming is slower but general, and writing those same problems as LPs teaches two things: how to turn a combinatorial question into variables and constraints, and why some of these LPs have integer optimal solutions for free. This lesson formulates single-pair shortest paths, maximum flow and minimum-cost flow as LPs, solves them with SciPy and checks each answer against a combinatorial algorithm.
Shortest paths: a maximization
Let be a directed graph with edge weights , a source and a target . Give every vertex a variable and write
The constraints are the triangle inequalities that the true distances satisfy (Relaxation). It may seem odd that a shortest path is a maximization, but the constraints only bound from above: along any path they add up to , so is at most the length of every path, and the largest value it can take is the shortest length. Minimizing would just send every to . These are the same difference constraints as in Difference Constraints and Shortest Paths, read in the other direction.
from scipy.optimize import linprog
V = ["s", "a", "b", "c", "t"]
E = [("s", "a", 4), ("s", "b", 1), ("b", "a", 2), ("a", "c", 1), ("b", "c", 5), ("c", "t", 3), ("a", "t", 6)]
idx = {v: i for i, v in enumerate(V)}
A_ub, b_ub = [], []
for u, v, w in E: # d_v - d_u <= w
row = [0] * len(V); row[idx[v]] = 1; row[idx[u]] = -1
A_ub.append(row); b_ub.append(w)
A_eq, b_eq = [[1 if v == "s" else 0 for v in V]], [0]
c = [-1 if v == "t" else 0 for v in V] # maximize d_t = minimize -d_t
res = linprog(c, A_ub=A_ub, b_ub=b_ub, A_eq=A_eq, b_eq=b_eq, bounds=[(None, None)] * len(V), method="highs")
print("LP value d_t =", round(-res.fun, 6))
dist = {v: float("inf") for v in V}; dist["s"] = 0
for _ in range(len(V) - 1): # Bellman-Ford as the referee
for u, v, w in E:
dist[v] = min(dist[v], dist[u] + w)
print("Bellman-Ford distances:", dist)
tight = [(u, v) for u, v, w in E if dist[v] == dist[u] + w]
print("tight edges (where the constraint holds with equality):", tight)LP value d_t = 7.0
Bellman-Ford distances: {'s': 0, 'a': 3, 'b': 1, 'c': 4, 't': 7}
tight edges (where the constraint holds with equality): [('s', 'b'), ('b', 'a'), ('a', 'c'), ('c', 't')]
The tight edges contain the shortest path of length 7. (The LP's other variables are not unique: any below its distance that keeps the constraints is allowed, because only is maximized.)
Maximum flow
A flow network has capacities on its edges, a source and a sink (Flow Networks). With one variable per edge, the maximum flow problem is
The LP has variables and equations plus the bounds. The program solves it and compares with a short Edmonds-Karp implementation.
from collections import deque
from scipy.optimize import linprog
V = ["s", "a", "b", "c", "d", "t"]
E = [("s", "a", 10), ("s", "b", 8), ("a", "b", 2), ("a", "c", 5), ("b", "d", 10),
("c", "t", 7), ("d", "c", 4), ("d", "t", 6)]
c = [-1 if u == "s" else 0 for u, v, cap in E] # maximize the flow out of s
A_eq = [[(1 if v == x else 0) - (1 if u == x else 0) for u, v, cap in E] for x in V if x not in "st"]
res = linprog(c, A_eq=A_eq, b_eq=[0] * len(A_eq), bounds=[(0, cap) for u, v, cap in E], method="highs")
print("LP max flow:", round(-res.fun, 6))
print("every edge flow of the LP vertex is an integer:", all(abs(f - round(f)) < 1e-9 for f in res.x))
def edmonds_karp(V, E, s, t):
r = {}
for u, v, cap in E:
r[(u, v)] = r.get((u, v), 0) + cap
r.setdefault((v, u), 0)
total = 0
while True:
parent, q = {s: None}, deque([s])
while q and t not in parent:
u = q.popleft()
for x in V:
if x not in parent and r.get((u, x), 0) > 0:
parent[x] = u; q.append(x)
if t not in parent:
return total
path, x = [], t
while parent[x] is not None:
path.append((parent[x], x)); x = parent[x]
b = min(r[e] for e in path)
for u, v in path:
r[(u, v)] -= b; r[(v, u)] += b
total += b
print("Edmonds-Karp:", edmonds_karp(V, E, "s", "t"))LP max flow: 13.0
every edge flow of the LP vertex is an integer: True
Edmonds-Karp: 13
Both find 13. The solver returns a vertex of the feasible polytope, and that vertex is integral although nothing in the LP asked for integers. (Several flows reach 13 here, so the solver may pick any of them; all its vertices are integral.)
Why the answers come out integral
The constraint matrix of the flow LP is the incidence matrix of the directed graph: every column (edge) has one and one . Such matrices are totally unimodular: every square submatrix has determinant , or . By Cramer's rule, every vertex of is then integral whenever and are integral. That is the LP explanation of the integrality theorem for flows, and the reason why LP methods solve bipartite matching and many scheduling problems exactly. The shortest-path LP's matrix is the transpose of an incidence matrix, also totally unimodular, so its vertex solutions are integral for integer weights.
Minimum-cost flow
Now each edge also has a cost per unit of flow, and the task is to send exactly units from to as cheaply as possible:
Min-cost flow generalizes both earlier problems: shortest paths are min-cost flows of one unit with unlimited capacities, and maximum flow is a min-cost flow with cost on an extra edge from back to . It has fast combinatorial algorithms too, but the LP is a one-liner to write down.
from scipy.optimize import linprog
V = ["s", "a", "b", "t"]
E = [("s", "a", 4, 2), ("s", "b", 2, 2), ("a", "b", 2, 1), ("a", "t", 3, 3), ("b", "t", 5, 1)] # (u, v, capacity, cost)
D = 5
A_eq = [[(1 if v == x else 0) - (1 if u == x else 0) for u, v, cap, cost in E] for x in V if x not in "st"]
A_eq.append([(1 if u == "s" else 0) - (1 if v == "s" else 0) for u, v, cap, cost in E])
b_eq = [0] * (len(V) - 2) + [D]
res = linprog([cost for *_, cost in E], A_eq=A_eq, b_eq=b_eq,
bounds=[(0, cap) for u, v, cap, cost in E], method="highs")
print("minimum cost of sending", D, "units:", round(res.fun, 6))
for (u, v, cap, cost), f in zip(E, res.x):
print(f" {u}->{v}: {round(f, 6)} of {cap} at cost {cost} each")minimum cost of sending 5 units: 19.0
s->a: 3.0 of 4 at cost 2 each
s->b: 2.0 of 2 at cost 2 each
a->b: 2.0 of 2 at cost 1 each
a->t: 1.0 of 3 at cost 3 each
b->t: 4.0 of 5 at cost 1 each
The cheap route (cost 3 per unit) is saturated at its first edge's capacity 2; the next cheapest, (cost 4 per unit), takes 2 more until edge is full; the last unit uses at cost 5. Total .
Problems only LP solves in polynomial time
Some flow problems have no known polynomial algorithm other than linear programming. In multicommodity flow, several pairs each need units of their own commodity through shared capacities. The LP has one variable per commodity per edge and adds the capacity constraint . The matrix is no longer totally unimodular, so integer solutions are not guaranteed (and finding integral multicommodity flows is NP-hard), but the fractional problem is solved in polynomial time by LP. Duality, the deeper reason why max flow equals min cut and why shortest-path LPs have the shape they do, is developed in Linear Programming & Duality for Algorithms and in LP Duality.
In C++
A certificate check in C++: given Bellman-Ford distances, verify that they satisfy every LP constraint (feasibility) and that the target's value is achieved by a path of tight edges (so no feasible can be larger). Together that proves optimality without any LP solver.
#include <cstdio>
#include <vector>
struct Edge { int u, v, w; };
int main() {
const char* name = "sabct";
std::vector<Edge> E = {{0, 1, 4}, {0, 2, 1}, {2, 1, 2}, {1, 3, 1}, {2, 3, 5}, {3, 4, 3}, {1, 4, 6}};
const int n = 5, INF = 1 << 29;
std::vector<int> d(n, INF), parent(n, -1);
d[0] = 0;
for (int round = 0; round < n - 1; round++)
for (auto [u, v, w] : E)
if (d[u] + w < d[v]) { d[v] = d[u] + w; parent[v] = u; }
bool feasible = true;
for (auto [u, v, w] : E) feasible = feasible && d[v] <= d[u] + w;
std::printf("all %zu constraints d_v <= d_u + w hold: %s\n", E.size(), feasible ? "yes" : "no");
std::printf("tight path to t:");
std::vector<int> path;
for (int x = 4; x != -1; x = parent[x]) path.insert(path.begin(), x);
for (int x : path) std::printf(" %c", name[x]);
std::printf(", length %d = d_t\n", d[4]);
}all 7 constraints d_v <= d_u + w hold: yes
tight path to t: s b a c t, length 7 = d_t
Test yourself
Why is the single-pair shortest-path LP a maximization of ?
- Because the weights are negative
- Because the constraints only bound from above by every path length, so its largest feasible value is the shortest length
- Because LPs must maximize
- Because the minimum is always 0
What do the conservation constraints of the max-flow LP say?
- Every edge carries at most its capacity
- At every vertex other than and , the flow in equals the flow out
- The flow out of equals its capacity
- All flows are integers
Why does the max-flow LP have integral optimal vertices when the capacities are integers?
- Because the solver rounds
- Because its constraint matrix (an incidence matrix) is totally unimodular
- Because flows are always integers
- Because the graph is acyclic
Which problem is known to be solvable in polynomial time mainly through linear programming?
- Single-source shortest paths
- Maximum flow
- Fractional multicommodity flow
- Minimum spanning tree