This repository has been archived by the owner on Jul 6, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
MaximumMatchingBipartiteGraph.scala
63 lines (52 loc) · 1.69 KB
/
MaximumMatchingBipartiteGraph.scala
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
import scala.collection.mutable
object MaximumMatchingBipartiteGraph {
// Function to find maximum matching in a bipartite graph
def maximumMatching(graph: Array[Array[Boolean]], m: Int, n: Int): Array[Int] = {
// Array to store matching of n vertices, -1 indicates no match
val matchR = Array.fill(n)(-1)
// Try to find an augmenting path
def bpm(u: Int, seen: Array[Boolean], matchR: Array[Int]): Boolean = {
for (v <- 0 until n) {
if (graph(u)(v) && !seen(v)) {
seen(v) = true
if (matchR(v) == -1 || bpm(matchR(v), seen, matchR)) {
matchR(v) = u
return true
}
}
}
false
}
// Count of maximum matching
var result = 0
// Iterate through all vertices on left side
for (u <- 0 until m) {
// Array to track which vertices are visited in this DFS
val seen = Array.fill(n)(false)
// Find if the vertex u can be matched to a vertex on right side
if (bpm(u, seen, matchR))
result += 1
}
matchR
}
def main(args: Array[String]): Unit = {
// Example usage:
val m = 4 // Number of vertices in set U
val n = 4 // Number of vertices in set V
// Example adjacency matrix representation of the bipartite graph
val graph = Array(
Array(false, true, true, false),
Array(true, false, false, true),
Array(false, false, true, false),
Array(false, false, true, false)
)
val matchR = maximumMatching(graph, m, n)
// Print the maximum matching
println("Maximum Matching:")
for (i <- 0 until n) {
if (matchR(i) != -1) {
println(s"Vertex $matchR(i) matches with vertex $i")
}
}
}
}