코딩테스트 준비

백준 알고스팟 - 우선순위 큐, 너비우선탐색

언어 수집가 2021. 3. 21. 19:06
m, n = map(int, input().split())
import sys
import heapq
ground = []
visited = [[False]*m for _ in range(n)]
for i in range(n):
ground.append(list(sys.stdin.readline().rstrip()))
dx = [1, 0, -1, 0]
dy = [0, 1, 0, -1]
res = []
if n == m == 1:
print(0)
exit(0)
def bfs(x, y):
a = []
heapq.heappush(a, (0, x, y))
visited[x][y] = True
while a:
v, x, y = heapq.heappop(a)
for i in range(4):
nx = x + dx[i]
ny = y + dy[i]
if 0 <= nx < n and 0 <= ny < m:
if nx == n-1 and ny == m-1:
res.append(v)
elif not visited[nx][ny]:
new = v + int(ground[nx][ny])
heapq.heappush(a, (new, nx, ny))
visited[nx][ny] = True
bfs(0, 0)
print(min(res))