private static void MaxFlow(FlowGraph graph) { while (true) { var foundPath = false; var queue = new Queue <int>(); var parentIds = new int[graph.Size()]; for (var i = 0; i < parentIds.Length; i++) { parentIds[i] = -1; } queue.Enqueue(0); //bfs while (queue.Count > 0 && !foundPath) { var node = queue.Dequeue(); var ids = graph.GetIds(node); foreach (var id in ids) { var edge = graph.GetEdge(id); if (edge.Flow < edge.Capacity && parentIds[edge.To] == -1) { if (edge.To == edge.From) { continue; } parentIds[edge.To] = id; if (edge.To == graph.Size() - 1) { foundPath = true; break; } queue.Enqueue(edge.To); } } } if (!foundPath) { break; } //find the value of the flow var to = graph.Size() - 1; var minCapacity = -1; while (to != 0) { var id = parentIds[to]; var edge = graph.GetEdge(id); if (minCapacity == -1 || (edge.Capacity - edge.Flow) < minCapacity) { minCapacity = edge.Capacity - edge.Flow; } to = edge.From; } to = graph.Size() - 1; while (to != 0) { var id = parentIds[to]; var edge = graph.GetEdge(id); graph.AddFlow(id, minCapacity); to = edge.From; } } }