110 lines
2.3 KiB
Python
110 lines
2.3 KiB
Python
map = []
|
|
moves = ""
|
|
with open("input") as f:
|
|
for line in f:
|
|
if line == "\n":
|
|
break
|
|
map.append(line.rstrip("\n"))
|
|
moves = f.readline().strip()
|
|
|
|
F = {
|
|
0: (+1, 0),
|
|
1: (0, +1),
|
|
2: (-1, 0),
|
|
3: (0, -1),
|
|
}
|
|
|
|
#assert len(set(len(l) for l in map)) == 1
|
|
|
|
|
|
class Map:
|
|
def __init__(self, map):
|
|
self.map = map
|
|
self.starts = {}
|
|
for row in range(len(self.map)):
|
|
i = 0
|
|
while self.map[row][i] == ' ':
|
|
i += 1
|
|
self.starts[row] = i
|
|
self.row = 0
|
|
self.col = self.starts[0]
|
|
self.face = 0
|
|
|
|
def nextTile(self):
|
|
x,y = self.col, self.row
|
|
f = self.face
|
|
# 0 - E
|
|
# 1 - S
|
|
# 2 - W
|
|
# 3 - N
|
|
dx, dy = F[self.face]
|
|
|
|
if dx:
|
|
x += dx
|
|
if x < self.starts[y]:
|
|
x = len(self.map[y])-1
|
|
elif x >= len(self.map[y]):
|
|
x = self.starts[y]
|
|
|
|
if dy:
|
|
for _ in range(999):
|
|
y += dy
|
|
if y < 0:
|
|
y = len(self.map)-1
|
|
elif y >= len(self.map):
|
|
y = 0
|
|
if x > len(self.map[y]) or self.map[y][x] == ' ':
|
|
continue
|
|
break
|
|
|
|
assert self.map[y][x] != ' '
|
|
return x, y, self.map[y][x]
|
|
|
|
def turnLeft(self):
|
|
self.face = (self.face - 1) % 4
|
|
def turnRight(self):
|
|
self.face = (self.face + 1) % 4
|
|
def walk(self, n):
|
|
while n > 0:
|
|
x,y,c = self.nextTile()
|
|
if c == '#':
|
|
break
|
|
self.row = y
|
|
self.col = x
|
|
#self.map[y][x] = '>v<^'[self.face]
|
|
n -= 1
|
|
print(self.row, self.col)
|
|
|
|
def pos(self):
|
|
return self.row+1, self.col+1
|
|
|
|
def score(self):
|
|
r, c = self.pos()
|
|
return r*1000 + c *4 + self.face
|
|
|
|
print(moves)
|
|
|
|
m = Map(map)
|
|
|
|
i = 0
|
|
while i < len(moves):
|
|
if moves[i].isdigit():
|
|
j = i+1
|
|
while j < len(moves) and moves[j].isdigit():
|
|
j += 1
|
|
n = int(moves[i:j])
|
|
m.walk(n)
|
|
i = j
|
|
elif moves[i] == 'L':
|
|
m.turnLeft()
|
|
i += 1
|
|
elif moves[i] == 'R':
|
|
m.turnRight()
|
|
i += 1
|
|
else:
|
|
print("invalid move", moves[i], "at", i)
|
|
i += 1
|
|
|
|
print(m.row, m.col)
|
|
print(m.score())
|