-
Notifications
You must be signed in to change notification settings - Fork 0
/
part1.py
87 lines (65 loc) · 2.69 KB
/
part1.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
# Description: Day 23 Part 1 of Advent of Code
def solution(textfile: str) -> int:
""" Return the number of steps of the longest hike """
# Artifact due to change of the template
lines = textfile.splitlines()
lines = [line+"\n" for line in lines]
lines[-1] = lines[-1][:-1]
# End of artifact
graph = {}
for i, line in enumerate(lines):
for j, c in enumerate(line.strip()):
if c == '.':
graph[(i, j)] = []
if i > 0:
top = lines[i-1][j]
if top != '#' and top != 'v':
graph[(i, j)].append((i-1, j))
if i < len(lines) - 1:
bottom = lines[i+1][j]
if bottom != '#' and bottom != '^':
graph[(i, j)].append((i+1, j))
if j > 0:
left = lines[i][j-1]
if left != '#' and left != '>':
graph[(i, j)].append((i, j-1))
if j < len(line) - 1:
right = lines[i][j+1]
if right != '#' and right != '<':
graph[(i, j)].append((i, j+1))
elif c == '^':
graph[(i, j)] = []
if i > 0:
top = lines[i-1][j]
if top != '#' and top != 'v':
graph[(i, j)].append((i-1, j))
elif c == 'v':
graph[(i, j)] = []
if i < len(lines) - 1:
bottom = lines[i+1][j]
if bottom != '#' and bottom != '^':
graph[(i, j)].append((i+1, j))
elif c == '<':
graph[(i, j)] = []
if j > 0:
left = lines[i][j-1]
if left != '#' and left != '>':
graph[(i, j)].append((i, j-1))
elif c == '>':
graph[(i, j)] = []
if j < len(line) - 1:
right = lines[i][j+1]
if right != '#' and right != '<':
graph[(i, j)].append((i, j+1))
start = (0, lines[0].index('.'))
end = (len(lines) - 1, lines[-1].index('.'))
distance = 0
remains = [(start, [start])]
while remains:
current, path = remains.pop(0)
for neighbor in graph[current]:
if neighbor == end:
distance = max(distance, len(path) + 1)
elif neighbor not in path :
remains.append((neighbor, path + [neighbor]))
return distance - 1 # we need the number of steps