diff --git a/Graphs/FordFulkerson.js b/Graphs/FordFulkerson.js new file mode 100644 index 0000000000..f53d10c4b0 --- /dev/null +++ b/Graphs/FordFulkerson.js @@ -0,0 +1,52 @@ +// https://en.wikipedia.org/wiki/Ford%E2%80%93Fulkerson_algorithm +function fordFulkerson(capacity, source, sink) { + const V = capacity.length; + const residualCapacity = capacity.map((arr) => arr.slice()); + const parent = Array(V).fill(-1); + let maxFlow = 0; + + function bfs(source, sink) { + const visited = Array(V).fill(false); + const queue = [source]; + visited[source] = true; + parent[source] = -1; + + while (queue.length > 0) { + const u = queue.shift(); + + for (let v = 0; v < V; v++) { + if (!visited[v] && residualCapacity[u][v] > 0) { + if (v === sink) { + parent[v] = u; + return true; + } + queue.push(v); + parent[v] = u; + visited[v] = true; + } + } + } + return false; + } + + while (bfs(source, sink)) { + let pathFlow = Infinity; + for (let v = sink; v !== source; v = parent[v]) { + const u = parent[v]; + pathFlow = Math.min(pathFlow, residualCapacity[u][v]); + } + + for (let v = sink; v !== source; v = parent[v]) { + const u = parent[v]; + residualCapacity[u][v] -= pathFlow; + residualCapacity[v][u] += pathFlow; + } + + maxFlow += pathFlow; + } + + return maxFlow; +} + +export { fordFulkerson }; + \ No newline at end of file diff --git a/Graphs/test/FordFulkerson.test.js b/Graphs/test/FordFulkerson.test.js new file mode 100644 index 0000000000..89f36868d3 --- /dev/null +++ b/Graphs/test/FordFulkerson.test.js @@ -0,0 +1,46 @@ +import { fordFulkerson } from '../FordFulkerson.js' + +test('Test Case 1', () => { + const capacity = [ + [0, 16, 13, 0, 0, 0], + [0, 0, 10, 12, 0, 0], + [0, 4, 0, 0, 14, 0], + [0, 0, 9, 0, 0, 20], + [0, 0, 0, 7, 0, 4], + [0, 0, 0, 0, 0, 0], + ] + const source = 0 + const sink = 5 + const maxFlow = fordFulkerson(capacity, source, sink) + expect(maxFlow).toBe(23) +}) + +test('Test Case 2', () => { + const capacity = [ + [0, 10, 0, 10, 0, 0], + [0, 0, 5, 0, 15, 0], + [0, 0, 0, 0, 10, 10], + [0, 0, 10, 0, 0, 10], + [0, 0, 0, 0, 0, 10], + [0, 0, 0, 0, 0, 0], + ] + const source = 0 + const sink = 5 + const maxFlow = fordFulkerson(capacity, source, sink) + expect(maxFlow).toBe(20) +}) + +test('Test Case 3', () => { + const capacity = [ + [0, 7, 0, 0, 3, 0], + [0, 0, 5, 0, 2, 0], + [0, 0, 0, 8, 0, 7], + [0, 0, 0, 0, 0, 5], + [0, 0, 0, 5, 0, 0], + [0, 0, 0, 0, 0, 0], + ] + const source = 0 + const sink = 5 + const maxFlow = fordFulkerson(capacity, source, sink) + expect(maxFlow).toBe(10) +})