Browse Source

Solve 2021 day 12

Taddeus Kroes 4 năm trước cách đây
mục cha
commit
1238c12493
2 tập tin đã thay đổi với 54 bổ sung0 xóa
  1. 29 0
      2021/12_paths.py
  2. 25 0
      2021/input/12

+ 29 - 0
2021/12_paths.py

@@ -0,0 +1,29 @@
+#!/usr/bin/env python3
+import sys
+
+def parse(f):
+    graph = {}
+    for line in f:
+        a, b = line.rstrip().split('-')
+        graph.setdefault(a, []).append(b)
+        graph.setdefault(b, []).append(a)
+    return graph
+
+def paths(graph, may_dup):
+    work = [(('start',), not may_dup)]
+    distinct = 0
+    while work:
+        path, dup = work.pop()
+        if path[-1] == 'end':
+            distinct += 1
+        else:
+            for nb in graph[path[-1]]:
+                if nb.isupper() or nb not in path:
+                    work.append((path + (nb,), dup))
+                elif not dup and nb != 'start':
+                    work.append((path + (nb,), True))
+    return distinct
+
+graph = parse(sys.stdin)
+print(paths(graph, False))
+print(paths(graph, True))

+ 25 - 0
2021/input/12

@@ -0,0 +1,25 @@
+YW-end
+DK-la
+la-XG
+end-gy
+zq-ci
+XG-gz
+TF-la
+xm-la
+gy-gz
+ci-start
+YW-ci
+TF-zq
+ci-DK
+la-TS
+zq-YW
+gz-YW
+zq-gz
+end-gz
+ci-TF
+DK-zq
+gy-YW
+start-DK
+gz-DK
+zq-la
+start-TF