This commit is contained in:
79
day-12/day-12.py
Normal file
79
day-12/day-12.py
Normal file
@@ -0,0 +1,79 @@
|
||||
#!/usr/bin/env python3
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def process_node(node, available_edges, visited):
|
||||
paths = []
|
||||
if node == "end":
|
||||
return [[node]]
|
||||
if node.islower():
|
||||
visited.add(node)
|
||||
neighbors = [[n for n in e if n != node]
|
||||
for e in available_edges if node in e]
|
||||
for n in neighbors:
|
||||
n = n[0]
|
||||
if n not in visited:
|
||||
next = process_node(n, available_edges, visited)
|
||||
for p in next:
|
||||
paths.append([node] + p)
|
||||
if node in visited:
|
||||
visited.remove(node)
|
||||
return paths
|
||||
|
||||
|
||||
def process_node_twice(node, available_edges, visited, twice):
|
||||
paths = []
|
||||
if node == "end":
|
||||
return [[node]]
|
||||
if node.islower():
|
||||
if node in visited and twice:
|
||||
return paths
|
||||
elif node in visited and node != "start":
|
||||
twice = node
|
||||
else:
|
||||
visited.add(node)
|
||||
neighbors = [[n for n in e if n != node]
|
||||
for e in available_edges if node in e]
|
||||
for n in neighbors:
|
||||
n = n[0]
|
||||
if n not in visited or twice != node and n != "start":
|
||||
next = process_node_twice(n, available_edges, visited, twice)
|
||||
for p in next:
|
||||
paths.append([node] + p)
|
||||
if twice == node:
|
||||
twice = ""
|
||||
elif node in visited:
|
||||
visited.remove(node)
|
||||
return paths
|
||||
|
||||
|
||||
def part_1(input):
|
||||
result = 0
|
||||
edges = []
|
||||
for line in input:
|
||||
n_start, n_end = line.strip().split('-')
|
||||
e = (n_start, n_end)
|
||||
edges.append(e)
|
||||
paths = process_node("start", edges, set())
|
||||
result = len(paths)
|
||||
print("Part 1 result:", result)
|
||||
|
||||
|
||||
def part_2(input):
|
||||
result = 0
|
||||
edges = []
|
||||
for line in input:
|
||||
n_start, n_end = line.strip().split('-')
|
||||
e = (n_start, n_end)
|
||||
edges.append(e)
|
||||
paths = process_node_twice("start", edges, set(), "")
|
||||
result = len(paths)
|
||||
print("Part 2 result:", result)
|
||||
|
||||
|
||||
input = list()
|
||||
p = Path(__file__).with_name('input.txt')
|
||||
with open(p) as f:
|
||||
input = f.readlines()
|
||||
part_1(input)
|
||||
part_2(input)
|
||||
24
day-12/input.txt
Normal file
24
day-12/input.txt
Normal file
@@ -0,0 +1,24 @@
|
||||
pf-pk
|
||||
ZQ-iz
|
||||
iz-NY
|
||||
ZQ-end
|
||||
pf-gx
|
||||
pk-ZQ
|
||||
ZQ-dc
|
||||
NY-start
|
||||
NY-pf
|
||||
NY-gx
|
||||
ag-ZQ
|
||||
pf-start
|
||||
start-gx
|
||||
BN-ag
|
||||
iz-pf
|
||||
ag-FD
|
||||
pk-NY
|
||||
gx-pk
|
||||
end-BN
|
||||
ag-pf
|
||||
iz-pk
|
||||
pk-ag
|
||||
iz-end
|
||||
iz-BN
|
||||
Reference in New Issue
Block a user