AdventOfCode/2017/24/test.py

59 lines
1.5 KiB
Python
Raw Normal View History

2024-11-30 23:15:29 +01:00
from collections import defaultdict
import pprint
def build_graph(pairs):
graph = defaultdict(list)
for pair in pairs:
a, b = map(int, pair.split('/'))
graph[a].append(b)
graph[b].append(a)
return graph
def find_all_paths(graph, start, visited=None, path=None):
if visited is None:
visited = set()
if path is None:
path = []
visited.add(start)
path.append(start)
paths = [list(path)] # Store the current path as a possible connection
for neighbor in graph[start]:
if neighbor not in visited:
paths.extend(find_all_paths(graph, neighbor, visited.copy(), path.copy()))
return paths
def count_connections(pairs):
graph = build_graph(pairs)
all_paths = []
for pair in pairs:
a, b = map(int, pair.split('/'))
paths_a = find_all_paths(graph, a)
paths_b = find_all_paths(graph, b)
# Combine paths starting from both nodes in the pair
for path in paths_a:
if b in path:
all_paths.append(path)
for path in paths_b:
if a in path:
all_paths.append(path)
# Remove duplicate paths
unique_paths = {tuple(path) for path in all_paths}
return len(unique_paths), unique_paths
# Example usage
pairs = ['0/2','2/2','2/3','3/4','3/5','0/1','10/1','9/10']
connection_count, connections = count_connections(pairs)
print(f"Number of connections: {connection_count}")
print("Connections:")
for connection in connections:
print(connection)
pprint(connections)