728x90
반응형
최단경로를 찾아야 되는 기본적인 BFS 문제이다.
from collections import deque
def bfs():
queue = deque()
queue.append((0, 0))
d = [(0, 1), (0, -1), (1, 0), (-1, 0)]
while queue:
y, x = queue.popleft()
for dy, dx in d:
Y, X = y+dy, x+dx
if (0 <= Y < N) and (0 <= X < M) and graph[Y][X] == 1:
graph[Y][X] = graph[y][x] + 1
queue.append((Y, X))
N, M = map(int, input().split())
graph = [list(map(int, list(input()))) for _ in range(N)]
bfs()
print(graph[N-1][M-1])
728x90
반응형
'Agorithm > 백준 알고리즘' 카테고리의 다른 글
백준 알고리즘 2667번 단지번호붙이기(python) (0) | 2021.03.10 |
---|---|
백준 알고리즘 2606번 바이러스(python) (0) | 2021.03.10 |
백준 알고리즘 7562번 나이트의 이동(python) (0) | 2021.03.10 |
백준 알고리즘 1260번 DFS와 BFS(python) (0) | 2021.03.10 |
백준 알고리즘 1012번 유기농 배추(python) (0) | 2021.03.10 |