File tree Expand file tree Collapse file tree 2 files changed +97
-0
lines changed Expand file tree Collapse file tree 2 files changed +97
-0
lines changed Original file line number Diff line number Diff line change 1+ // https://en.wikipedia.org/wiki/Ford%E2%80%93Fulkerson_algorithm
2+ function 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+ }
28+ }
29+ return false
30+ }
31+
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
46+ }
47+ return maxFlow
48+ }
49+
50+ export { fordFulkerson }
51+
Original file line number Diff line number Diff line change 1+ import { fordFulkerson } from '../FordFulkerson.js'
2+
3+ test ( 'Test Case 1' , ( ) => {
4+ const capacity = [
5+ [ 0 , 16 , 13 , 0 , 0 , 0 ] ,
6+ [ 0 , 0 , 10 , 12 , 0 , 0 ] ,
7+ [ 0 , 4 , 0 , 0 , 14 , 0 ] ,
8+ [ 0 , 0 , 9 , 0 , 0 , 20 ] ,
9+ [ 0 , 0 , 0 , 7 , 0 , 4 ] ,
10+ [ 0 , 0 , 0 , 0 , 0 , 0 ] ,
11+ ]
12+ const source = 0
13+ const sink = 5
14+ const maxFlow = fordFulkerson ( capacity , source , sink )
15+ expect ( maxFlow ) . toBe ( 23 )
16+ } )
17+
18+ test ( 'Test Case 2' , ( ) => {
19+ const capacity = [
20+ [ 0 , 10 , 0 , 10 , 0 , 0 ] ,
21+ [ 0 , 0 , 5 , 0 , 15 , 0 ] ,
22+ [ 0 , 0 , 0 , 0 , 10 , 10 ] ,
23+ [ 0 , 0 , 10 , 0 , 0 , 10 ] ,
24+ [ 0 , 0 , 0 , 0 , 0 , 10 ] ,
25+ [ 0 , 0 , 0 , 0 , 0 , 0 ] ,
26+ ]
27+ const source = 0
28+ const sink = 5
29+ const maxFlow = fordFulkerson ( capacity , source , sink )
30+ expect ( maxFlow ) . toBe ( 20 )
31+ } )
32+
33+ test ( 'Test Case 3' , ( ) => {
34+ const capacity = [
35+ [ 0 , 7 , 0 , 0 , 3 , 0 ] ,
36+ [ 0 , 0 , 5 , 0 , 2 , 0 ] ,
37+ [ 0 , 0 , 0 , 8 , 0 , 7 ] ,
38+ [ 0 , 0 , 0 , 0 , 0 , 5 ] ,
39+ [ 0 , 0 , 0 , 5 , 0 , 0 ] ,
40+ [ 0 , 0 , 0 , 0 , 0 , 0 ] ,
41+ ]
42+ const source = 0
43+ const sink = 5
44+ const maxFlow = fordFulkerson ( capacity , source , sink )
45+ expect ( maxFlow ) . toBe ( 10 )
46+ } )
You can’t perform that action at this time.
0 commit comments