| 41 | } |
| 42 | |
| 43 | func EdmondKarp(graph WeightedGraph, source int, sink int) float64 { |
| 44 | // Check graph emptiness |
| 45 | if len(graph) == 0 { |
| 46 | return 0.0 |
| 47 | } |
| 48 | |
| 49 | // Check correct dimensions of the graph slice |
| 50 | for i := 0; i < len(graph); i++ { |
| 51 | if len(graph[i]) != len(graph) { |
| 52 | return 0.0 |
| 53 | } |
| 54 | } |
| 55 | |
| 56 | rGraph := make(WeightedGraph, len(graph)) |
| 57 | for i := 0; i < len(graph); i++ { |
| 58 | rGraph[i] = make([]float64, len(graph)) |
| 59 | } |
| 60 | // Init the residual graph with the same capacities as the original graph |
| 61 | copy(rGraph, graph) |
| 62 | |
| 63 | maxFlow := 0.0 |
| 64 | |
| 65 | for { |
| 66 | parent := FindPath(rGraph, source, sink) |
| 67 | if parent == nil { |
| 68 | break |
| 69 | } |
| 70 | // Finding the max flow over the path returned by BFS |
| 71 | // i.e. finding minimum residual capacity amonth the path edges |
| 72 | pathFlow := math.MaxFloat64 |
| 73 | for v := sink; v != source; v = parent[v] { |
| 74 | u := parent[v] |
| 75 | if rGraph[u][v] < pathFlow { |
| 76 | pathFlow = rGraph[u][v] |
| 77 | } |
| 78 | } |
| 79 | |
| 80 | // update residual capacities of the edges and |
| 81 | // reverse edges along the path |
| 82 | for v := sink; v != source; v = parent[v] { |
| 83 | u := parent[v] |
| 84 | rGraph[u][v] -= pathFlow |
| 85 | rGraph[v][u] += pathFlow |
| 86 | } |
| 87 | |
| 88 | // Update the total flow found so far |
| 89 | maxFlow += pathFlow |
| 90 | } |
| 91 | |
| 92 | return maxFlow |
| 93 | } |