-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFordFulkerson.m
89 lines (66 loc) · 1.54 KB
/
FordFulkerson.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
function [f, cap] = FordFulkerson(CapMatrix, S, T)
cap = CapMatrix;
f = 0;
while true
% Hallar
path = findPath(cap, S, T);
if path(1) == 0
break
end
% Flujo
flow = max(max(cap));
for j = 2:length(path)
flow = min(flow, cap(path(j), path(j-1)));
end
for j = 2:length(path)
a = path(j); b = path(j-1);
cap(a,b) = cap(a,b) - flow;
cap(b,a) = cap(b,a) + flow;
end
f = f + flow;
end
end
function F = findPath(CapMatrix, S, T)
% BFS (Breadth-first Search)
% Número de nodos
n = length(CapMatrix);
% Contadores de frente y trasero
front = 1;
back = 2;
% Fila (queue)
queue = zeros(1,n);
queue(front) = S;
% Iniciar conjunto de predecesores
pred = zeros(1,n);
pred(S) = S;
while front ~= back
% Elegimos nuevo nodo y aumentamos 1 a frente
node = queue(front);
front = front + 1;
% Iterar sobre todos los nodos
for i = 1:n
% Si el nodo no es predecesor y la capacidad máxima es positiva,
% agregarlo a la cola y aumentar 1 al contador de trasero 'back'.
% Además, actualizar el predecesor
if pred(i) == 0 && CapMatrix(node,i) > 0
queue(back) = i;
back = back + 1;
pred(i) = node;
end
end
end
% Iniciar variable de camino
path = zeros(1,n);
if pred(T) ~= 0
i = T; c = 1;
while pred(i) ~= i
path(c) = i;
c = c + 1;
i = pred(i);
end
path(c) = S;
path(c+1:n) = [];
end
% Devolver camino final
F = path;
end