Created
November 18, 2013 01:08
-
-
Save Eyas/7520781 to your computer and use it in GitHub Desktop.
Edmonds Karp in C#
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
namespace Algorithms | |
{ | |
/// Edmonds Karp MaxFlow Algorithm | |
/// based on en.wikipedia.org/wiki/Edmonds%E2%80%93Karp_algorithm | |
public class EdmondsKarp { | |
private int n = 0; | |
public int FindMaxFlow( | |
int[,] capacityMatrix, | |
Dictionary<int, List<int>> neighbors, | |
int source, | |
int sink, | |
out int[,] legalFlows) | |
{ | |
n = capacityMatrix.GetLength(0); | |
int f = 0; // initial flow is 0 | |
legalFlows = new int[n, n]; // residual capacity from u to v is capacityMatrix[u,v] - legalFlows[u,v] | |
while(true) | |
{ | |
int[] p; | |
int m = BreadthFirstSearch(capacityMatrix, neighbors, source, sink, legalFlows, out p); | |
if (m == 0) break; | |
f += m; | |
// backtrakc search, and write flow | |
int v = sink; | |
while (v != source) | |
{ | |
int u = p[v]; | |
legalFlows[u, v] += m; | |
legalFlows[v, u] -= m; | |
v = u; | |
} | |
} | |
return f; | |
} | |
private int BreadthFirstSearch( | |
int[,] capacityMatrix, | |
Dictionary<int, List<int>> neighbors, | |
int source, | |
int sink, | |
int[,] legalFlows, | |
out int[] p) | |
{ | |
p = new int[n]; | |
for (int u = 0; u <n; u++) | |
{ | |
p[u] = -1; | |
} | |
p[source] = -2; // make sure source is not rediscovered | |
int[] m = new int[n]; // capacity of found path to node | |
m[source] = int.MaxValue; | |
Queue<int> q = new Queue<int>(); | |
q.Enqueue(source); | |
while (q.Count > 0) | |
{ | |
int u = q.Dequeue(); | |
foreach (int v in neighbors[u]) | |
{ | |
// if there is available capacity, and v is not seen before in search | |
if (capacityMatrix[u, v] - legalFlows[u, v] > 0 && | |
p[v] == -1) | |
{ | |
p[v] = u; | |
m[v] = Math.Min(m[u], capacityMatrix[u,v] - legalFlows[u,v]); | |
if (v != sink) q.Enqueue(v); | |
else return m[sink]; | |
} | |
} | |
} | |
return 0; | |
} | |
} | |
} |
Hello! Can you please show example input data for EdmondsKarp().FindMaxFlow(...)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hey there -- its not really a fully written program, just an implementation of the algorithm. You can copy this into your source and just call
new EdmondsKarp().FindMaxFlow(...)
from any function (orMain
) that you have.