BOJ - 2665 - 미로만들기

Updated:

import sys
from heapq import heappush, heappop

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

def Dijkstra(graph, N):
    heap = []
    distance = [[INF] * N 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 == N-1:
            return weight

        for i in range(4):
            nx = x + dx[i]
            ny = y + dy[i]

            if 0 <= nx < N and 0 <= ny < N:
                w = weight + graph[nx][ny]
                if w < distance[nx][ny]:
                    distance[nx][ny] = w
                    heappush(heap, (w, nx, ny))

def solution():
    N = int(input())
    graph = []
    for _ in range(N):
        graph.append(list(str(sys.stdin.readline().strip())))

    for i in range(N):
        for j in range(N):
            if graph[i][j] == '1':
                graph[i][j] = 0
            else:
                graph[i][j] = 1

    print(Dijkstra(graph, N))

solution()

https://www.acmicpc.net/problem/2665

Categories:

Updated:

Leave a comment