띠리링구 2022. 4. 30. 02:38

[ACM-ICPC] 화성탐사 — 열정은 차갑고 잔잔하게 (tistory.com)

 

[ACM-ICPC] 화성탐사

입력 예시 3 3 5 5 4 3 9 1 3 2 7 5 3 7 2 0 1 2 8 0 9 1 1 2 1 8 1 9 8 9 2 0 3 6 5 1 5 7 9 0 5 1 1 5 3 4 1 2 1 6 5 3 0 7 6 1 6 8 5 1 1 7 8 3 2 3 9 8 0 7 6 4 1 5 8 3 2 4 8 3 7 4 8 4 8 3 4 출력예시 20 1..

ksabs.tistory.com

 

N * N grid를 그래프 삼아 다익스트라를 수행하면 된다. 2차원리스트이기 때문에 최단경로 저장 리스트 역시 2차원. 2차원 버전의 다익스트라라고 보면 될거같다.

 

import heapq

N = int(input())
INF = 1e10

grid = []
for _ in range(N):
    grid.append(list(map(int,input().split())))

#padding
grid = list(map(lambda x: [-INF] + x + [-INF],  grid))
grid.insert(0, [-INF] * (N + 2))
grid.append([-INF] * (N + 2))

cost = [[INF] * (N + 2) for _ in range(N + 2)]

dx = [0, 0, -1, 1]
dy = [1, -1, 0, 0]

q = []

cost[1][1] = grid[1][1]
heapq.heappush(q, (cost[1][1],1,1) )

while q:
    cur_cost, row, col = heapq.heappop(q)

    if row == 0 or col == 0 or row == N + 1 or col == N + 1:
        continue

    if cost[row][col] < cur_cost:
        continue

    for i in range(4):
        nxt_row = row + dx[i]
        nxt_col = col + dy[i]
        nxt_cost = grid[nxt_row][nxt_col] + cur_cost

        if cost[nxt_row][nxt_col] > nxt_cost:
            cost[nxt_row][nxt_col] = nxt_cost
            heapq.heappush(q,(nxt_cost, nxt_row, nxt_col))

print(cost[N][N])