Skip to content

Instantly share code, notes, and snippets.

@skhokhlov
Created December 27, 2015 17:08
Show Gist options
  • Save skhokhlov/69a1becf4032f0fa754b to your computer and use it in GitHub Desktop.
Save skhokhlov/69a1becf4032f0fa754b to your computer and use it in GitHub Desktop.
'use strict';
var fs = require('fs');
function Ford(m, s, f) {
let mf = new Array(m.length).fill(new Array(m.length).fill(0));
let link = new Array(m.length).fill(0);
let flow = new Array(m.length).fill(0);
function findPath(s, f) {
let q = [];
flow[s] = Infinity;
link[f] = -1;
q.push(s);
while(link[f] === -1 && q.length) {
const t = q.pop();
for (let i = 0; i < m.length; ++i) {
if((m[t][i] - mf[t][i]) > 0 && flow[i] === 0) {
q.unshift(i);
link[i] = t;
flow[i] = (m[t][i] - mf[t][i]) < flow[t] ? m[t][i] : flow[t];
}
}
}
if (link[f] === -1) {
return 0;
}
let t = f;
while (t !== s) {
mf[link[t]][t] += flow[f];
t = link[t];
}
return flow[f];
}
let maxFlow = 0;
let a;
do {
a = findPath(s, f);
maxFlow += a;
} while (a > 0);
return maxFlow;
}
fs.readFile('graph.txt', 'utf-8', function (err, data) {
if (err) {
throw new Error(err);
}
data = data.split('\n');
let matrix = [];
for (let i in data) {
if (data[i] != '') {
matrix.push(data[i].split(' '));
}
}
for (let i in matrix) {
for (let j in matrix[i]) {
matrix[i][j] = Number(matrix[i][j]);
}
}
console.log(Ford(matrix, 0, 5));
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment