Repository navigation
Expand file tree
/
Copy path10.py
More file actions
140 lines (122 loc) · 2.9 KB
/
Copy path10.py
File metadata and controls
140 lines (122 loc) · 2.9 KB
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
import sys
import pytest
from pathlib import Path
from textwrap import dedent
START = "S"
VERTICAL_PIPE = "|"
HORIZONTAL_PIPE = "-"
NORTH_TO_EAST = "L"
NORTH_TO_WEST = "J"
SOUTH_TO_EAST = "F"
SOUTH_TO_WEST = "7"
UP = "up"
DOWN = "down"
LEFT = "left"
RIGHT = "right"
def get_start(maze: list[str]) -> tuple[int, int]:
for i in range(len(maze)):
for j in range(len(maze[i])):
if maze[i][j] == START:
return (i, j)
return (0, 0)
def solve(text: str) -> int:
maze = text.splitlines()
i, j = get_start(maze)
direction = None
# Up
if i > 0 and maze[i - 1][j] in [VERTICAL_PIPE, SOUTH_TO_EAST, SOUTH_TO_WEST]:
i -= 1
direction = UP
# Down
elif i < len(maze) - 1 and maze[i + 1][j] in [
VERTICAL_PIPE,
NORTH_TO_EAST,
NORTH_TO_WEST,
]:
i += 1
direction = DOWN
# Left
elif j > 0 and maze[i][j - 1] in [HORIZONTAL_PIPE, SOUTH_TO_EAST, NORTH_TO_EAST]:
j -= 1
direction = LEFT
# Right
elif j < len(maze[i]) - 1 and maze[i][j + 1] in [
HORIZONTAL_PIPE,
SOUTH_TO_WEST,
NORTH_TO_WEST,
]:
j += 1
direction = RIGHT
steps = 1
while maze[i][j] != START:
pipe = maze[i][j]
if pipe == VERTICAL_PIPE:
if direction == UP:
i -= 1
else:
i += 1
elif pipe == SOUTH_TO_EAST:
if direction == UP:
j += 1
direction = RIGHT
else:
i += 1
direction = DOWN
elif pipe == HORIZONTAL_PIPE:
if direction == LEFT:
j -= 1
else:
j += 1
elif pipe == SOUTH_TO_WEST:
if direction == UP:
j -= 1
direction = LEFT
else:
i += 1
direction = DOWN
elif pipe == NORTH_TO_WEST:
if direction == DOWN:
j -= 1
direction = LEFT
else:
i -= 1
direction = UP
elif pipe == NORTH_TO_EAST:
if direction == DOWN:
j += 1
direction = RIGHT
else:
i -= 1
direction = UP
steps += 1
return steps // 2
if __name__ == "__main__":
p = Path(sys.argv[1])
print(solve(p.read_text()))
def test():
text = dedent(
"""
-L|F7
7S-7|
L|7||
-L-J|
L|-JF
"""
).strip()
assert solve(text) == 4
text = dedent(
"""
7-F7-
.FJ|7
SJLL7
|F--J
LJ.LJ
"""
).strip()
assert solve(text) == 8
def test_input():
p = Path("10.txt")
if not p.exists():
pytest.skip(f"{p} does not exist")
text = p.read_text()
assert solve(text) == 6800