aoc2024/d23/part2_bron_kerbosch.py

24 lines
602 B
Python
Raw Normal View History

from collections import defaultdict as DD
import sys
G = DD(set)
for line in sys.stdin.read().strip().split('\n'):
a, b = line.split('-')
G[a].add(b)
G[b].add(a)
def bron_kerbosch(r, p, x):
if len(p) == 0 and len(x) == 0:
yield r
else:
pivot = max(p | x, key=lambda x: len(G[x]))
for v in p - G[pivot]:
neighbours = G[v]
yield from bron_kerbosch(r | {v}, p & neighbours, x & neighbours)
p.remove(v)
x.add(v)
clique = max(bron_kerbosch(set(), set(G.keys()), set()), key=len)
print(','.join(sorted(clique)))