Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 624b25e

Browse files
committedOct 2, 2024·
Added Ford Fulkerson algorithm for Hacktoberfest contribution
1 parent 9010481 commit 624b25e

File tree

2 files changed

+97
-0
lines changed

2 files changed

+97
-0
lines changed
 

‎Graphs/FordFulkerson.js

+51
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
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+

‎Graphs/test/FordFulkerson.test.js

+46
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
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+
})

0 commit comments

Comments
 (0)
Please sign in to comment.