다익스트라 풀이
import heapq
# N = int(input())
N, M = map(int, input().split())
INF = 1e9
dp = [[INF for _ in range(N)] for _ in range(M)]
map_lst = [list(map(int, input())) for _ in range(M)]
dx = [-1, 0, 1, 0]
dy = [0, -1, 0, 1]
def dijkstra(x, y):
q = []
heapq.heappush(q, (map_lst[y][x], x, y))
dp[y][x] = map_lst[y][x]
while q:
wall, x, y = heapq.heappop(q)
# 이미 처리된 곳이면
if dp[y][x] < wall:
continue
for i in range(4):
nx = x + dx[i]
ny = y + dy[i]
# 인덱스 범위 벗어난 경우는 무시
if nx < 0 or nx >= N or ny < 0 or ny >= M:
continue
cost = wall + map_lst[ny][nx]
# 기존 값보다 작으면
if dp[ny][nx] > cost:
dp[ny][nx] = cost
heapq.heappush(q, (cost, nx, ny))
dijkstra(0, 0)
print(dp[-1][-1])
BFS 풀이
from collections import deque
N, M = map(int, input().split())
INF = 1e9
dp = [[INF for _ in range(N)] for _ in range(M)]
map_lst = [list(map(int, input())) for _ in range(M)]
dx = [-1, 0, 1, 0]
dy = [0, -1, 0, 1]
def bfs(x, y):
q = deque([(x, y, 0)])
dp[y][x] = map_lst[y][x]
while q:
x, y, wall = q.popleft()
# 이미 처리된 곳이면
if dp[y][x] < wall:
continue
for i in range(4):
nx = x + dx[i]
ny = y + dy[i]
# 인덱스 범위 벗어난 경우는 무시
if nx < 0 or nx >= N or ny < 0 or ny >= M:
continue
cost = wall + map_lst[ny][nx]
# 기존 값보다 작으면
if dp[ny][nx] > cost:
dp[ny][nx] = cost
q.append((nx, ny, cost))
bfs(0, 0)
print(dp[-1][-1])