BOJ - 1261 - 알고스팟
Updated:
import sys
from heapq import heappush, heappop
dx = [1, -1, 0, 0]
dy = [0, 0, 1, -1]
INF = 1e9
def Dijkstra(graph, N, M):
heap = []
distance = [[INF] * M for _ in range(N)]
heappush(heap, (graph[0][0], 0, 0))
distance[0][0] = 0
while heap:
weight, x, y = heappop(heap)
if x == N-1 and y == M-1:
return weight
for i in range(4):
nx = x + dx[i]
ny = y + dy[i]
if 0 <= nx < N and 0 <= ny < M:
w = weight + graph[nx][ny]
if w < distance[nx][ny]:
distance[nx][ny] = w
heappush(heap, (w, nx, ny))
def solution():
M, N = map(int, sys.stdin.readline().split())
graph = []
for _ in range(N):
graph.append(list(str(sys.stdin.readline().strip())))
for i in range(N):
for j in range(M):
graph[i][j] = int(graph[i][j])
print(Dijkstra(graph, N, M))
solution()
https://www.acmicpc.net/problem/1261
Leave a comment