DevYoon
[๋ฐฑ์ค] 1261. ์๊ณ ์คํ (Python) ๋ณธ๋ฌธ
link ๐ https://www.acmicpc.net/problem/1261
๐ฅ BFS
๐ฅ visit ๋ฐฐ์ด์ ๋ฒฝ์ ๋ถ์ ํ์๋ฅผ ๊ธฐ๋กํ๋ฉฐ BFS๋ฅผ ๋๋ฆฐ๋ค.
๐ฅ ๋ฒฝ์ ๋ถ์ด์ผ ํ ๊ฒฝ์ฐ +1, ๋ฒฝ์ ๋ถ์์ง ์์๋ ๋๋ ๊ฒฝ์ฐ ํ์ฌ ์์น์ ํ์๋ฅผ ๊ทธ๋๋ก ๊ฐ์ ธ๊ฐ๊ณ , appendleft๋ก ๋งจ ์์ ๋ฃ์ด์ค๋ค.
from collections import deque
X, Y = map(int, input().split())
board = [list(map(int, input())) for _ in range(Y)]
visit = [[0]*X for _ in range(Y)]
def BFS():
q = deque()
q.append((0, 0))
visit[0][0] = 1
dir = [(-1, 0), (1, 0), (0, -1), (0, 1)]
while q:
ny, nx = q.popleft()
for i, j in dir:
dy, dx = ny+i, nx+j
if 0 <= dy < Y and 0 <= dx < X:
if visit[dy][dx] == 0:
if board[dy][dx] == 0:
visit[dy][dx] = visit[ny][nx]
q.appendleft((dy, dx))
else:
visit[dy][dx] = visit[ny][nx]+1
q.append((dy, dx))
BFS()
print(visit[Y-1][X-1]-1)