@@ -2,6 +2,35 @@ package eu.sim642.adventofcodelib.graph
2
2
3
3
object BronKerbosch {
4
4
5
+ // unused
6
+ def maximalCliques [A ](neighbors : Map [A , Set [A ]]): Iterator [Set [A ]] = {
7
+
8
+ def bronKerbosch (r : Set [A ], p : Set [A ], x : Set [A ]): Iterator [Set [A ]] = {
9
+ if (p.isEmpty) {
10
+ if (x.isEmpty)
11
+ Iterator .single(r)
12
+ else
13
+ Iterator .empty
14
+ }
15
+ else {
16
+ // val u = p.headOption.getOrElse(x.head)
17
+ val u = (p ++ x).maxBy(neighbors(_).size) // pivot on highest degree
18
+ val vs = (p -- neighbors(u)).iterator
19
+ Iterator .unfold((p, x))((p, x) => // foldLeftFlatMap
20
+ vs.nextOption().map(v =>
21
+ (bronKerbosch(r + v, p intersect neighbors(v), x intersect neighbors(v)), (p - v, x + v))
22
+ )
23
+ ).flatten
24
+ }
25
+ }
26
+
27
+ bronKerbosch(Set .empty, neighbors.keySet, Set .empty)
28
+ }
29
+
30
+ // TODO: would this be slower than direct implementation below?
31
+ /* def maximumClique[A](neighbors: Map[A, Set[A]]): Set[A] =
32
+ maximalCliques(neighbors).maxBy(_.size)*/
33
+
5
34
// moved from 2018 day 23
6
35
def maximumClique [A ](neighbors : Map [A , Set [A ]]): Set [A ] = {
7
36
var best : Set [A ] = Set .empty
0 commit comments