-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path15-2.py
104 lines (90 loc) · 2.39 KB
/
15-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
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
# pylint: skip-file
# mypy: ignore-errors
# flake8: noqa
from collections import defaultdict
input_value = open("15.txt", "r").read()
[grid_raw, moves] = input_value.split("\n\n")
grid_raw = grid_raw.split("\n")
rows = len(grid_raw)
columns = len(grid_raw[0])
moves = "".join(moves.split("\n"))
grid = defaultdict(lambda: "#")
robot = None
for r in range(rows):
for c in range(columns):
if grid_raw[r][c] == "#":
grid[r, 2 * c] = "#"
grid[r, 2 * c + 1] = "#"
if grid_raw[r][c] == "O":
grid[r, 2 * c] = "["
grid[r, 2 * c + 1] = "]"
if grid_raw[r][c] == ".":
grid[r, 2 * c] = "."
grid[r, 2 * c + 1] = "."
if grid_raw[r][c] == "@":
grid[r, 2 * c] = "@"
grid[r, 2 * c + 1] = "."
robot = (r, 2 * c)
# Debug:
columns *= 2
# out = ""
# for r in range(rows):
# for c in range(columns):
# out += grid[r, c]
# out += "\n"
# print(out)
# input()
def move_frontier(rr, rc, dr, dc):
global grid
move_set = set()
frontier = [(rr, rc)]
while frontier:
(r, c) = frontier.pop()
if (r, c) in move_set or grid[r, c] == ".":
continue
move_set.add((r, c))
if grid[r, c] == "[":
frontier.append((r, c + 1))
elif grid[r, c] == "]":
frontier.append((r, c - 1))
if grid[r + dr, c + dc] == "#":
return (rr, rc)
frontier.append((r + dr, c + dc))
grid_saved = {}
for r, c in move_set:
grid_saved[r, c] = grid[r, c]
grid[r, c] = "."
for r, c in move_set:
grid[r + dr, c + dc] = grid_saved[r, c]
return (rr + dr, rc + dc)
# Debug:
# out = ""
# for r in range(rows):
# for c in range(columns):
# out += grid[r, c]
# out += "\n"
# print(out)
# input()
for move in moves:
(rr, rc) = robot
if move == ">":
robot = move_frontier(rr, rc, 0, 1)
elif move == "<":
robot = move_frontier(rr, rc, 0, -1)
elif move == "v":
robot = move_frontier(rr, rc, 1, 0)
elif move == "^":
robot = move_frontier(rr, rc, -1, 0)
# Debug:
# out = ""
# for r in range(rows):
# for c in range(columns):
# out += grid[r, c]
# out += "\n"
# print(out)
# input()
total = 0
for r, c in grid:
if grid[r, c] == "[":
total += 100 * r + c
print(total)