알고리즘/[문제풀이] 백준
[백준] 2178 미로 탐색 (Python, BFS)
로그뉴
2021. 6. 6. 15:45
문제

코드
from collections import deque
n, m = map(int, input().split())
graph = []
for _ in range(n):
graph.append(list(map(int, input())))
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 nx < 0 or ny < 0 or nx >= n or ny >= m: # 가장자리 벽 pass
continue
if graph[nx][ny] == 0: # 0은 이동할 수 없기 때문에 pass
continue
if graph[nx][ny] == 1:
graph[nx][ny] = graph[x][y] + 1
q.append((nx,ny))
return graph[n-1][m-1]
print(bfs(0,0))
풀이
- 방향벡터 dx, dy를 잡아준다.
- bfs 알고리즘을 이용.
- 시작: queue에 (0,0)을 담아주기
- queue가 빌 때까지 계속 pop을 해주며 조건에 맞으면 queue에 다시 append.
- 조건1: 가장자리(첫 번째 if문)는 continue
- 조건2: 0인 칸(두 번째 if문)은 continue
- 조건3: 1인 칸(세 번째 if문)이면 graph[x][y] + 1 해준 값을 넣기. (칸을 이동할 때마다 1씩 증가하므로)
- 다 돌고 나면 graph[n-1][m-1]을 return하기