21922번: 학부 연구생 민상
from collections import deque
import sys
si = sys.stdin.readline
dxs = [-1, 0, 1, 0]
dys = [0, -1, 0, 1]
n, m = map(int, si().split())
visited = [[0] * m for _ in range(n)]
q = deque()
graph = []
for i in range(n):
line = list(map(int, si().split()))
for j in range(m):
if line[j] == 9:
q.append((i, j))
visited[i][j] = 1
graph.append(line)
def in_range(x, y):
return 0 <= x < n and 0 <= y < m
def bfs():
while q:
x, y = q.popleft()
for i in range(4):
dx, dy = dxs[i], dys[i]
nx, ny = x + dx, y + dy
while in_range(nx, ny):
visited[nx][ny] = 1
if graph[nx][ny] == 9:
break
if graph[nx][ny] == 3:
dx, dy = -dy, -dx
elif graph[nx][ny] == 4:
dx, dy = dy, dx
elif (graph[nx][ny] == 1 and dx == 0) or (graph[nx][ny] == 2 and dy == 0):
break
nx += dx
ny += dy
bfs()
answer = 0
for i in range(n):
for j in range(m):
if visited[i][j] == 1:
answer += 1
print(answer)