11// https://en.wikipedia.org/wiki/Ford%E2%80%93Fulkerson_algorithm
22function fordFulkerson ( capacity , source , sink ) {
3- const V = capacity . length
4- const residualCapacity = capacity . map ( arr => arr . slice ( ) )
5- const parent = Array ( V ) . fill ( - 1 )
6- let maxFlow = 0
7-
8- function bfs ( source , sink ) {
9- const visited = Array ( V ) . fill ( false )
10- const queue = [ source ]
11- visited [ source ] = true
12- parent [ source ] = - 1
13-
14- while ( queue . length > 0 ) {
15- const u = queue . shift ( )
16-
17- for ( let v = 0 ; v < V ; v ++ ) {
18- if ( ! visited [ v ] && residualCapacity [ u ] [ v ] > 0 ) {
19- if ( v === sink ) {
20- parent [ v ] = u
21- return true
22- }
23- queue . push ( v )
24- parent [ v ] = u
25- visited [ v ] = true
26- }
27- }
3+ const V = capacity . length ;
4+ const residualCapacity = capacity . map ( ( arr ) => arr . slice ( ) ) ;
5+ const parent = Array ( V ) . fill ( - 1 ) ;
6+ let maxFlow = 0 ;
7+
8+ function bfs ( source , sink ) {
9+ const visited = Array ( V ) . fill ( false ) ;
10+ const queue = [ source ] ;
11+ visited [ source ] = true ;
12+ parent [ source ] = - 1 ;
13+
14+ while ( queue . length > 0 ) {
15+ const u = queue . shift ( ) ;
16+
17+ for ( let v = 0 ; v < V ; v ++ ) {
18+ if ( ! visited [ v ] && residualCapacity [ u ] [ v ] > 0 ) {
19+ if ( v === sink ) {
20+ parent [ v ] = u ;
21+ return true ;
22+ }
23+ queue . push ( v ) ;
24+ parent [ v ] = u ;
25+ visited [ v ] = true ;
2826 }
29- return false
27+ }
3028 }
29+ return false ;
30+ }
3131
32- while ( bfs ( source , sink ) ) {
33- let pathFlow = Infinity
34- for ( let v = sink ; v !== source ; v = parent [ v ] ) {
35- const u = parent [ v ]
36- pathFlow = Math . min ( pathFlow , residualCapacity [ u ] [ v ] )
37- }
38-
39- for ( let v = sink ; v !== source ; v = parent [ v ] ) {
40- const u = parent [ v ]
41- residualCapacity [ u ] [ v ] -= pathFlow
42- residualCapacity [ v ] [ u ] += pathFlow
43- }
44-
45- maxFlow += pathFlow
32+ while ( bfs ( source , sink ) ) {
33+ let pathFlow = Infinity ;
34+ for ( let v = sink ; v !== source ; v = parent [ v ] ) {
35+ const u = parent [ v ] ;
36+ pathFlow = Math . min ( pathFlow , residualCapacity [ u ] [ v ] ) ;
4637 }
47- return maxFlow
38+
39+ for ( let v = sink ; v !== source ; v = parent [ v ] ) {
40+ const u = parent [ v ] ;
41+ residualCapacity [ u ] [ v ] -= pathFlow ;
42+ residualCapacity [ v ] [ u ] += pathFlow ;
43+ }
44+
45+ maxFlow += pathFlow ;
46+ }
47+
48+ return maxFlow ;
4849}
4950
50- export { fordFulkerson }
51+ export { fordFulkerson } ;
5152
0 commit comments