๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿƒ algorithm/boj

BOJ 14496 - ๊ทธ๋Œ€, ๊ทธ๋จธ๊ฐ€ ๋˜์–ด

by HandHand 2021. 3. 16.

๋ฌธ์ œ

๋ฐฑ์ค€ ์˜จ๋ผ์ธ ์ €์ง€ - 14496๋ฒˆ

ํ’€์ด ๊ณผ์ •

์‹œ์ž‘ ์ง€์ ์—์„œ ๋ชฉํ‘œ ์ง€์ ์— ๋„๋‹ฌํ•˜๊ธฐ ์œ„ํ•œ ์ตœ๋‹จ ๊ฒฝ๋กœ๋ฅผ ๊ตฌํ•˜๋Š” ๋ฌธ์ œ์ž…๋‹ˆ๋‹ค.

๋‹ค์ต์ŠคํŠธ๋ผ ์•Œ๊ณ ๋ฆฌ์ฆ˜ ์„ ํ™œ์šฉํ•ด์„œ ์‹œ์ž‘ ์ง€์ ์—์„œ ๋ชจ๋“  ์ง€์ ๊นŒ์ง€์˜ ๊ฑฐ๋ฆฌ๋ฅผ ๊ตฌํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

์ฝ”๋“œ


import sys
import heapq

INF = 2e9


def make_graph():
    graph = [[] for _ in range(n + 1)]

    for frm, to in edges:
        graph[frm].append(to)
        graph[to].append(frm)

    return graph


def dijkstra(graph):
    dist = [INF] * (n + 1)
    pq = []

    heapq.heappush(pq, [0, a])
    dist[a] = 0

    while pq:
        cost, here = heapq.heappop(pq)
        if dist[here] < cost:
            continue

        for there in graph[here]:
            next_cost = cost + 1
            if next_cost < dist[there]:
                dist[there] = next_cost
                heapq.heappush(pq, [next_cost, there])

    return dist


def solution():
    graph = make_graph()
    dist = dijkstra(graph)

    return dist[b] if dist[b] != INF else -1


if __name__ == '__main__':
    a, b = list(map(int, sys.stdin.readline().split()))
    n, m = list(map(int, sys.stdin.readline().split()))
    edges = [list(map(int, sys.stdin.readline().split())) for _ in range(m)]

    answer = solution()
    print(answer)



๋ฐ˜์‘ํ˜•

'๐Ÿƒ algorithm > boj' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

BOJ 14754 - Pizza Boxes  (0) 2021.03.18
BOJ 15723 - n๋‹จ ๋…ผ๋ฒ•  (0) 2021.03.18
BOJ 9311 - Robot in a Maze  (0) 2021.03.14
BOJ 20005 - ๋ณด์Šค๋ชฌ์Šคํ„ฐ ์ „๋ฆฌํ’ˆ  (0) 2021.03.14
BOJ 17521 - Byte Coin  (0) 2021.03.14

๐Ÿ’ฌ ๋Œ“๊ธ€