221. 미로 탐색

아현·2021년 7월 20일
0

Algorithm

목록 보기
231/400

백준




1. Python



import sys
from collections import deque
input = sys.stdin.readline
n, m = map(int,input().split())
maze = [list(map(int, input().rstrip())) for _ in range(n)]

dx = [-1, 1, 0, 0]
dy = [0, 0, -1, 1]

def bfs(x, y):
  q = deque()
  q.append((x, y))
  while q:
    x, y = q.popleft()
    for i in range(4):
      nx = x + dx[i]
      ny = y + dy[i]

      if 0 <= nx < n and 0 <= ny < m:
        if maze[nx][ny] == 1:
          maze[nx][ny] = maze[x][y] + 1
          q.append((nx, ny))
  
  return maze[n - 1][m - 1]

print(bfs(0,0))



profile
Studying Computer Science

0개의 댓글