aboutsummaryrefslogtreecommitdiff
path: root/2021/day12
diff options
context:
space:
mode:
authorAria <me@aria.rip>2023-01-02 21:58:56 +0000
committerAria <me@aria.rip>2023-01-02 21:58:56 +0000
commit5eb58ad076f2cd435b11b140820da224b60b73d5 (patch)
tree2a67939595fbf993ff04f69b9cd3f0aa20827d96 /2021/day12
initial commit
Diffstat (limited to '2021/day12')
-rw-r--r--2021/day12/12a.py34
-rw-r--r--2021/day12/12b.py32
2 files changed, 66 insertions, 0 deletions
diff --git a/2021/day12/12a.py b/2021/day12/12a.py
new file mode 100644
index 0000000..5d1adba
--- /dev/null
+++ b/2021/day12/12a.py
@@ -0,0 +1,34 @@
+from collections import deque
+
+def parseInput(contents):
+ edges = [l.split("-") for l in contents.strip().split("\n")]
+ edges_set = set([])
+ for (f, t) in edges:
+ edges_set.add((f, t))
+ if t != "end" and f != "start":
+ edges_set.add((t, f))
+
+ return edges_set
+
+def visitableNeighbours(edges, loc):
+ fr = loc[0]
+ banned = [e for e in loc if e.islower()]
+ for (f, t) in edges:
+ if f == fr and t not in banned:
+ yield t
+
+
+edges = parseInput(open("./input").read())
+
+locs = deque() # each element is a list of all the visited nodes
+finished = set()
+locs.append(["start"])
+while len(locs) > 0:
+ l = locs.pop()
+ if l[0] == "end":
+ finished.add("-".join(l))
+ else:
+ for neighbour in visitableNeighbours(edges, l):
+ locs.append([neighbour] + l)
+
+print(len(finished))
diff --git a/2021/day12/12b.py b/2021/day12/12b.py
new file mode 100644
index 0000000..149749e
--- /dev/null
+++ b/2021/day12/12b.py
@@ -0,0 +1,32 @@
+from collections import deque
+
+def parseInput(contents):
+ edges = [l.split("-") for l in contents.strip().split("\n")]
+ edges_set = set([])
+ for (f, t) in edges:
+ edges_set.add((f, t))
+ if t != "end" and f != "start":
+ edges_set.add((t, f))
+
+ return edges_set
+
+def visitableNeighbours(edges, path, doubleVisited):
+ curr = path[0]
+ banned = [e for e in path if e.islower()] if doubleVisited else ["start"]
+ for (f, t) in edges:
+ if f == curr and t not in banned:
+ yield t
+
+
+edges = parseInput(open("./input").read())
+
+locs = deque() # each element is a tuple of (double visited, list of all the visited nodes)
+finished = set()
+locs.append((False, ["start"]))
+while len(locs) > 0:
+ doubleVisited, path = locs.pop()
+ if path[0] == "end":
+ finished.add("-".join(path))
+ else:
+ for neighbour in visitableNeighbours(edges, path, doubleVisited):
+ locs.append((doubleVisited or (neighbour.islower() and neighbour in path), [neighbour] + path))