Hello, I'm currently trying to get a ford fulkerson implementation working that uses priority first search. The problem is that it seems to get in an endless loop, specifically the last while-loop in the pfs function. The prev[to] is always 5, so the guard of the while-loop is always true and so it never terminates.
I'm having a lot of trouble finding information on ford fulkerson using a priority first search, this is the best information i could find: http://community.topcoder.com/tc?module=Static&d1=tutorials&d2=maxFlow. Any help getting this working would be really appreciated.I'm pretty sure it's something small, but I can't seem to find it.
Thanks.
I'm having a lot of trouble finding information on ford fulkerson using a priority first search, this is the best information i could find: http://community.topcoder.com/tc?module=Static&d1=tutorials&d2=maxFlow. Any help getting this working would be really appreciated.I'm pretty sure it's something small, but I can't seem to find it.
Thanks.
public static void main(String[] args) {
// the graph
int capacity[][] = new int[6][6];
int n = 6;
capacity[0][1] = 16;
capacity[0][2] = 13;
capacity[1][2] = 10;
capacity[2][1] = 4;
capacity[3][2] = 9;
capacity[1][3] = 12;
capacity[2][4] = 14;
capacity[4][3] = 7;
capacity[3][5] = 20;
capacity[4][5] = 4;
int maxflow = maxflow(capacity, n, 0, 5);
}
static int maxflow(int[][] c, int n, int s, int t) {
int flow = 0;
while (true) {
int path = pfs(c, n, s, t);
if (path <= 0) {
break;
} else {
flow += path;
}
}
return(flow);
}
private static int pfs(int[][] capacity, int n, int source, int sink) {
Queue<Node> pq = new PriorityQueue<Node>();
pq.add(new Node(source, Integer.MAX_VALUE, -1));
int[] prev = new int[n];
Arrays.fill(prev, -1);
boolean[] visit = new boolean[n];
Arrays.fill(visit, false);
int flow = 0;
while (!pq.isEmpty()) {
Node top = pq.poll();
int from = top.from;
if (visit[from]) { }
prev[from] = top.from;
if (from == sink) {
flow = top.flow;
break;
}
visit[from] = true;
for (int i = 0; i < n; i++) {
if (capacity[from][i] > 0) {
int newFlow = Math.min(capacity[from][i], top.flow);
pq.add(new Node(i, newFlow, from));
}
}
}
if (flow == 0) {
return 0;
}
int to = sink;
// this loop never ends
while (prev[to] != -1) {
capacity[prev[to]][to] -= flow;
capacity[to][prev[to]] += flow;
to = prev[to];
}
return flow;
}
static class Node implements Comparable<Node> {
int from;
int flow;
int prev;
public Node(int from, int flow, int prev) {
this.from = from;
this.flow = flow;
this.prev = prev;
}
@Override
public int compareTo(Node that) {
return this.flow >= that.flow ? -1 : 1;
}
}