[백준/Python] 2178번 : 미로탐색

jhyngu·2023년 1월 31일
0

백준

목록 보기
10/12

문제

풀이

(0,0)부터 좌표를 한 칸씩 이동할 수 있는 부분에 전의 횟수에서 +1씩 하면 된다.
(0,0)에서 이동할 수 있는 좌표는 (1,0), (0,1)이므로 1에서 2로 바꿔준다.
다음으로 (1,0)에서 이동할 수 있는 좌표 (1,1), (2,0)는 2에서 3으로 바꿔준다.
이런식으로 반복해서 최솟값을 찾을 수 있다.

코드

# 2178 미로탐색

from collections import deque

n, m = map(int, input().split())
graph = []

for i in range(n):
  graph.append(list(map(int, input().rstrip())))

dx = [0,0,1,-1] # [상,하,좌,우]
dy = [1,-1,0,0] 

def bfs(a,b):
  queue = deque()
  queue.append([a,b])

  while queue:
    x, y = queue.popleft()

    for i in range(4):
      nx = x + dx[i]
      ny = y + dy[i]

      if nx >= n or ny >=m or nx < 0 or ny < 0:
        continue

      if graph[nx][ny] == 1:
        graph[nx][ny] = graph[x][y] + 1
        queue.append([nx,ny])

  return graph[n-1][m-1]

print(bfs(0,0))

결과

0개의 댓글