Skip to content

Commit e38b8f1

Browse files
committed
Day 12 in Python
1 parent e856a96 commit e38b8f1

File tree

5 files changed

+101
-0
lines changed

5 files changed

+101
-0
lines changed

day12.py

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
import sys
2+
from collections import defaultdict
3+
4+
class Path(object):
5+
def __init__(self, nodes, canVisitTwice=True) -> None:
6+
self.nodes = nodes
7+
self.canVisitTwice = canVisitTwice
8+
9+
def count_paths(connections, part2=False):
10+
paths = [ Path(["start"]) ]
11+
total = 0
12+
13+
while paths:
14+
path = paths.pop()
15+
lastNode = path.nodes[-1]
16+
for cave in connections[lastNode]:
17+
if cave == "end":
18+
total += 1
19+
elif part2 and cave == "start":
20+
continue
21+
elif cave not in path.nodes or cave.isupper(): # first visit, or a large cave
22+
paths.append( Path(path.nodes + [cave], path.canVisitTwice) )
23+
elif part2 and path.canVisitTwice: # a small cave visited twice in this path, allow no more
24+
paths.append( Path(path.nodes + [cave], False) )
25+
return total
26+
27+
def main(args = ()):
28+
fileName = "day12.txt" if len(args) < 1 else args[0]
29+
30+
connections = defaultdict(list)
31+
with open(fileName) as lines:
32+
for edge in lines:
33+
edge = edge.strip()
34+
if edge:
35+
a, b = edge.split("-")
36+
connections[a].append(b)
37+
connections[b].append(a)
38+
39+
print("Part 1:", count_paths(connections))
40+
print("Part 2:", count_paths(connections, True))
41+
42+
if __name__ == "__main__":
43+
sys.exit(main(sys.argv[1:]))

day12.txt

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
yw-MN
2+
wn-XB
3+
DG-dc
4+
MN-wn
5+
yw-DG
6+
start-dc
7+
start-ah
8+
MN-start
9+
fi-yw
10+
XB-fi
11+
wn-ah
12+
MN-ah
13+
MN-dc
14+
end-yw
15+
fi-end
16+
th-fi
17+
end-XB
18+
dc-XB
19+
yw-XN
20+
wn-yw
21+
dc-ah
22+
MN-fi
23+
wn-DG

day12sample1.txt

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
start-A
2+
start-b
3+
A-c
4+
A-b
5+
b-d
6+
A-end
7+
b-end

day12sample2.txt

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
dc-end
2+
HN-start
3+
start-kj
4+
dc-start
5+
dc-HN
6+
LN-dc
7+
HN-end
8+
kj-sa
9+
kj-HN
10+
kj-dc

day12sample3.txt

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
fs-end
2+
he-DX
3+
fs-he
4+
start-DX
5+
pj-DX
6+
end-zg
7+
zg-sl
8+
zg-pj
9+
pj-he
10+
RW-he
11+
fs-DX
12+
pj-RW
13+
zg-RW
14+
start-pj
15+
he-WI
16+
zg-he
17+
pj-fs
18+
start-RW

0 commit comments

Comments
 (0)