AdventOfCode/2017/24/test.py

68 lines
2.0 KiB
Python
Raw Normal View History

2024-12-01 23:24:40 +01:00
def build_graph(node_list):
"""
Build a graph where:
- Each graph starts with a node containing `0`.
- Nodes are connected if they share a common value, except `0` cannot connect to another `0`.
"""
graph = {}
# Parse nodes
parsed_nodes = [tuple(map(int, node.split('/'))) for node in node_list]
# Build adjacency list
for node1 in parsed_nodes:
for node2 in parsed_nodes:
# Skip if both nodes contain `0`
if node1 == node2 or (0 in node1 and 0 in node2):
continue
# Add edge if they share a common value
if node1[0] == node2[0] or node1[1] == node2[1] or node1[0] == node2[1] or node1[1] == node2[0]:
graph.setdefault(node1, []).append(node2)
graph.setdefault(node2, []).append(node1)
2024-11-30 23:15:29 +01:00
return graph
2024-12-01 23:24:40 +01:00
def find_paths(graph, start, visited=None, path=None):
"""
Recursively find all paths starting from a given node.
Ensures that each node is visited only once per path.
"""
2024-11-30 23:15:29 +01:00
if visited is None:
visited = set()
if path is None:
path = []
visited.add(start)
path.append(start)
2024-12-01 23:24:40 +01:00
# Print the current path
#print(" \--".join(f"{node[0]}/{node[1]}" for node in path))
# Explore neighbors
for neighbor in graph.get(start, []):
2024-11-30 23:15:29 +01:00
if neighbor not in visited:
2024-12-01 23:24:40 +01:00
find_paths(graph, neighbor, visited.copy(), path.copy())
return path
2024-11-30 23:15:29 +01:00
2024-12-01 23:24:40 +01:00
def main():
# Input list of nodes
nodes = [
"0/2", "2/2", "2/3", "3/4", "3/5", "0/1", "10/1", "9/10"
]
2024-11-30 23:15:29 +01:00
2024-12-01 23:24:40 +01:00
# Build the graph
graph = build_graph(nodes)
results = []
# Find and print all paths for each subgraph starting with a `0` node
zero_nodes = [node for node in graph if 0 in node]
for start in zero_nodes:
print(f"Starting from {start[0]}/{start[1]}:")
tmp = find_paths(graph, start)
results.append(tmp)
print(results)
2024-11-30 23:15:29 +01:00
2024-12-01 23:24:40 +01:00
if __name__ == "__main__":
main()