백준
1. 구현
from collections import deque
n = int(input())
k = int(input())
data = [[0] * (n + 1) for _ in range(n + 1)]
info = []
for _ in range(k):
a, b = map(int, input().split())
data[a][b] = 1
l = int(input())
for _ in range(l):
x, c = input().split()
info.append((int(x), c))
dx = [0, 1, 0, -1]
dy = [1, 0, -1, 0]
def turn(direction, c):
if c == "L":
direction = (direction - 1) % 4
else:
direction = (direction + 1) % 4
return direction
def simulate():
x, y = 1, 1
data[x][y] = 2
direction = 0
time = 0
index = 0
q = deque()
q.append((x, y))
while True:
nx = x + dx[direction]
ny = y + dy[direction]
if 1 <= nx and nx <= n and 1 <= ny and ny <= n and data[nx][ny] != 2:
if data[nx][ny] == 0:
data[nx][ny] = 2
q.append((nx, ny))
px, py = q.popleft()
data[px][py] = 0
if data[nx][ny] == 1:
data[nx][ny] = 2
q.append((nx, ny))
else:
time += 1
break
x, y = nx, ny
time += 1
if index < l and time == info[index][0]:
direction = turn(direction, info[index][1])
index += 1
return time
print(simulate())
2회
from collections import deque
n = int(input())
k = int(input())
graph = [[0] * (n + 1) for _ in range(n + 1)]
turn = []
for _ in range(k):
a, b = map(int, input().split())
graph[a][b] = 2
l = int(input())
for _ in range(l):
a, b = input().split()
turn.append((int(a), b))
dx = [0, 1, 0, -1]
dy = [1, 0, -1, 0]
def rotate(a, b):
if b == "L":
a = (a - 1) % 4
else:
a = (a + 1) % 4
return a
def bfs():
x, y = 1, 1
graph[x][y] = 1
direction = 0
time = 0
index = 0
q = deque()
q.append((x, y))
while True:
nx = x + dx[direction]
ny = y + dy[direction]
if 1 <= nx <= n and 1 <= ny <= n and graph[nx][ny] != 1:
if graph[nx][ny] == 0:
graph[nx][ny] = 1
q.append((nx, ny))
px, py = q.popleft()
graph[px][py] = 0
if graph[nx][ny] == 2:
graph[nx][ny] = 1
q.append((nx, ny))
else:
time += 1
break
x, y = nx, ny
time += 1
if index < l and time == turn[index][0]:
direction = rotate(direction, turn[index][1])
index += 1
return time
print(bfs())