Skip to content

Commit

Permalink
Improve BronKerbosch
Browse files Browse the repository at this point in the history
  • Loading branch information
loociano committed Jan 1, 2025
1 parent 01ec976 commit 7563145
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 4 deletions.
2 changes: 1 addition & 1 deletion aoc2024/src/day23/python/solution.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,4 +51,4 @@ def find_lan_password(connections: Sequence[str]) -> str:
maximal_cliques = []
find_maximal_cliques(r=set(), p=set(computers.keys()), x=set(), graph=computers, maximal_cliques=maximal_cliques)
maximum_clique = max(maximal_cliques, key=len) # Find the set with most interconnected computers.
return ','.join(maximum_clique)
return ','.join(sorted(maximum_clique))
8 changes: 5 additions & 3 deletions common/python3/graph_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ def shortest_distance_bfs(grid: list[list[str]], visited: set[Position] = None,


def find_maximal_cliques(r: set[str], p: set[str], x: set[str],
graph: dict[str, set[str]], maximal_cliques: list[tuple[str, ...]]) -> None:
graph: dict[str, set[str]], maximal_cliques: list[set[str]]) -> None:
"""Finds maximal cliques in an undirected graph.
Example usage:
graph: dict[str, set[str]]
Expand All @@ -69,10 +69,12 @@ def find_maximal_cliques(r: set[str], p: set[str], x: set[str],
# X := X ⋃ {v}
if not p and not x:
# R is a maximal clique.
maximal_cliques.append(tuple(sorted(r)))
if len(r) > 2: # Skip 1-vertex cliques (vertices) 2-vertex cliques (edges).
maximal_cliques.append(set(r)) # Copy R.
return
# Choose a pivot vertex u in P ⋃ X.
(d, pivot) = max([(len(graph[v]), v) for v in p.union(x)])
# Prefer pivots with more edges.
_, pivot = max([(len(graph[v]), v) for v in p.union(x)])
# For each vertex v in P \ N(u) do:
for v in p.difference(graph[pivot]):
find_maximal_cliques(r=r.union({v}), p=p.intersection(graph[v]), x=x.intersection(graph[v]),
Expand Down

0 comments on commit 7563145

Please sign in to comment.