Advertisement
alexandrajay2002

Advent of Code 2024 day 23 part 2

Dec 23rd, 2024
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.12 KB | Source Code | 0 0
  1. from collections import defaultdict
  2. from sys import argv
  3.  
  4.  
  5. def parse(src):
  6.     for line in src.splitlines():
  7.         if line == '':
  8.             continue
  9.         first, second = line.split('-', 1)
  10.         yield first.strip(), second.strip()
  11.  
  12.  
  13. def make_graph(connections):
  14.     graph = defaultdict(set)
  15.     for first, second in connections:
  16.         graph[first].add(second)
  17.         graph[second].add(first)
  18.     return graph
  19.  
  20.  
  21. def bron_kerbosch(graph, r, p, x):
  22.     def degree(node):
  23.         return len(graph[node])
  24.  
  25.     if len(p) == 0 and len(x) == 0:
  26.         yield r
  27.     else:
  28.         pivot = max(p | x, key=degree)
  29.         for v in p - graph[pivot]:
  30.             neighbors = graph[v]
  31.             yield from bron_kerbosch(
  32.                 graph, r | {v}, p & neighbours, x & neighbors)
  33.             p.remove(v)
  34.             x.add(v)
  35.  
  36.  
  37. def main(connections):
  38.     graph = make_graph(connections)
  39.     clique = max(bron_kerbosch(graph, set(), set(graph.keys()), set()),
  40.                  key=len)
  41.     return ','.join(sorted(clique))
  42.  
  43.  
  44. if __name__ == '__main__':
  45.     print(main(parse(open(argv[1]).read())))
  46.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement