function [F, maxf, V, S] = Ford_Fulkerson(C, src, sink) n = size(C, 1); F = zeros(n); maxf = 0; V = []; S = []; while true % in: ResNet. ResNet = C - F + F'; % residual network. % out: pre, Df pre = ones(1, n) * NaN; Df = ones(1, n) * inf; % DFS to find augmenting path. stk = [ src ]; unvisited = setdiff(1:n, src); while ~isempty(stk) if stk(1) == sink break; end % pop from = stk(1); stk(1) = []; % fot v in adj(u) [~, to] = find(ResNet(from, unvisited) > 0); tovisit = unvisited(unique(to)); % visit pre(tovisit) = from; Df(tovisit) = min(Df(from), ResNet(from, tovisit)); % push stk = [tovisit, stk]; unvisited = setdiff(unvisited, tovisit); end % DFS end. if isempty(stk) % not found. max flow get. S = setdiff(1:n, unvisited); V = unvisited; break; else % Augmenting path found. %in: pre, Df maxf = maxf + Df(sink); %update arc. t = sink; while t ~= src % pre(t)-t if C(pre(t), t) ~= 0 % forward arc. F(pre(t), t) = F(pre(t), t) + Df(sink); else % backward arc. F(t, pre(t)) = F(t, pre(t)) - Df(sink); end t = pre(t); end end end end