๋ฌธ์
๋ฐฑ์ค ์จ๋ผ์ธ ์ ์ง - 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 |
๐ฌ ๋๊ธ