|
1 |
| -from typing import TextIO, List, Dict, Tuple, Set |
| 1 | +from typing import TextIO, List, Dict, Tuple |
2 | 2 | import sys
|
3 | 3 | from collections import namedtuple, defaultdict
|
4 | 4 |
|
@@ -34,26 +34,41 @@ def read_input(textio: TextIO) -> Tuple[Dict[Node, List[Node]], Node, Node]:
|
34 | 34 | def print_paths(paths):
|
35 | 35 | for path in paths:
|
36 | 36 | 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]): |
39 | 43 | current_node = path_to_here[-1]
|
40 | 44 | adjacents = adjacency_list[current_node]
|
41 | 45 | for node in adjacents:
|
42 |
| - if not node.is_big and node in visited: |
43 |
| - continue |
44 |
| - |
45 | 46 | next_visited = visited.copy()
|
46 |
| - next_visited.add(node) |
| 47 | + next_visited[node] += 1 |
47 | 48 | next_path = list(path_to_here)
|
48 | 49 | next_path.append(node)
|
49 | 50 |
|
| 51 | + if node == start: |
| 52 | + continue |
| 53 | + |
50 | 54 | if node == end:
|
51 | 55 | 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): |
53 | 66 | go(adj, next_path, end, paths, next_visited)
|
54 | 67 |
|
55 | 68 | adj, start, end = read_input(sys.stdin)
|
56 | 69 | 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) |
58 | 73 | print(len(paths))
|
59 | 74 | # print_paths(paths)
|
0 commit comments