-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path6-2.py
52 lines (33 loc) · 1.05 KB
/
6-2.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
grid = open("puzzle.txt").read().splitlines()
rows = len(grid)
cols = len(grid[0])
guard = (0, 0)
steps = [(-1, 0), (0, 1), (1, 0), (0, -1)]
count = 0
for r in range(rows):
for c in range(cols):
if grid[r][c] == "^":
guard = (r, c)
def is_loop(guard, pos):
marked = set()
step_index = 0
new_grid = [list(line) for line in grid]
new_grid[pos[0]][pos[1]] = "#"
while True:
if (guard, step_index) in marked:
return True
marked.add((guard, step_index))
s_r, s_c = steps[step_index]
g_r, g_c = guard[0] + s_r, guard[1] + s_c
if not (0 <= g_r <= rows - 1 and 0 <= g_c <= cols - 1):
return False
elif (new_grid[g_r][g_c] == "#"):
step_index = (step_index + 1) % 4
else:
guard = (g_r, g_c)
for r in range(rows):
for c in range(cols):
if grid[r][c] == ".":
if (is_loop(guard, (r, c))):
count += 1
print(count)