Skip to content

Commit 2560e53

Browse files
committed
Day 12, Part 2
1 parent 378aaf5 commit 2560e53

File tree

1 file changed

+24
-9
lines changed

1 file changed

+24
-9
lines changed

day_12/__main__.py

Lines changed: 24 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
from typing import TextIO, List, Dict, Tuple, Set
1+
from typing import TextIO, List, Dict, Tuple
22
import sys
33
from collections import namedtuple, defaultdict
44

@@ -34,26 +34,41 @@ def read_input(textio: TextIO) -> Tuple[Dict[Node, List[Node]], Node, Node]:
3434
def print_paths(paths):
3535
for path in paths:
3636
print(','.join(node.name for node in path))
37-
38-
def go(adjacency_list: Dict[Node, List[Node]], path_to_here: List[Node], end: Node, paths, visited):
37+
38+
def already_double_visited_small_node(visited:Dict[Node, int]):
39+
ret = sum([1 for node, visit_count in visited.items() if not node.is_big and visit_count>1])
40+
return ret>1
41+
42+
def go(adjacency_list: Dict[Node, List[Node]], path_to_here: List[Node], end: Node, paths: List[List[Node]], visited:Dict[Node, int]):
3943
current_node = path_to_here[-1]
4044
adjacents = adjacency_list[current_node]
4145
for node in adjacents:
42-
if not node.is_big and node in visited:
43-
continue
44-
4546
next_visited = visited.copy()
46-
next_visited.add(node)
47+
next_visited[node] += 1
4748
next_path = list(path_to_here)
4849
next_path.append(node)
4950

51+
if node == start:
52+
continue
53+
5054
if node == end:
5155
paths.append(next_path)
52-
else:
56+
57+
elif node.is_big:
58+
# Can always visit big nodes
59+
go(adj, next_path, end, paths, next_visited)
60+
61+
elif visited[node] == 0:
62+
# Can always visit small nodes if they haven't been visited before
63+
go(adj, next_path, end, paths, next_visited)
64+
65+
elif not already_double_visited_small_node(visited):
5366
go(adj, next_path, end, paths, next_visited)
5467

5568
adj, start, end = read_input(sys.stdin)
5669
paths = []
57-
go(adj, [start], end, paths, set([start]))
70+
visited = defaultdict(lambda:0)
71+
visited[start] = 2
72+
go(adj, [start], end, paths, visited)
5873
print(len(paths))
5974
# print_paths(paths)

0 commit comments

Comments
 (0)