Last active
January 13, 2016 07:36
-
-
Save skhokhlov/c19c17b00961caeb98eb to your computer and use it in GitHub Desktop.
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
object FordFulkerson { | |
val capacity = Array( | |
Array(0, 1, 0), | |
Array(0, 0, 2), | |
Array(0, 0, 0) | |
) | |
def main(args: Array[String]): Unit = { | |
println(maxFlow(0, 2)) | |
println(capacity.deep.mkString("\n")) | |
} | |
def maxFlow(s: Int, t: Int): Int = { | |
var flow: Int = 0 | |
while (true) { | |
val b = Array.fill(capacity.length)(false) | |
val df: Int = findPath(b, s, t, Integer.MAX_VALUE) | |
if (df == 0) { | |
return flow | |
} | |
flow += df | |
} | |
0 | |
} | |
def findPath(vis: Array[Boolean], u: Int, t: Int, f: Int): Int = { | |
if (u == t) { | |
return f | |
} | |
vis(u) = true | |
for ((x, v) <- vis.view.zipWithIndex) { | |
if (!x && capacity(u)(v) > 0) { | |
val df = findPath(vis, v, t, Math.min(f, capacity(u)(v))) | |
if (df > 0) { | |
capacity(u)(v) -= df | |
capacity(v)(u) += df | |
return df | |
} | |
} | |
} | |
0 | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment