dijkstra
ํ๋ฆ
distance = [0, INF, INF,,,]
๊ฐ๋จํ ๊ตฌํ, ์๋ ๋๋ฆผ
import sys
INF = int(1e9)
# ๋
ธ๋์ ๊ฐ์, ๊ฐ์ ์ ๊ฐ
n, m = map(int,sys.stdin.readline().split())
# ์์ ๋
ธ๋ ๋ฒํธ ์
๋ ฅ
start = int(input())
# ๊ฐ ๋
ธ๋์ ์ฐ๊ฒฐ๋์ด ์๋ ๋
ธ๋์ ๋ํ ์ ๋ณด๋ฅผ ๋ด๋ ๋ฆฌ์คํธ
graph = [[] for i in range(n + 1)]
# ๋ฐฉ๋ฌธ ๋ฆฌ์คํธ
visited = [False] * (n + 1)
# ์ต๋จ ๊ฑฐ๋ฆฌ ํ
์ด๋ธ ๋ชจ๋ ๋ฌดํ์ผ๋ก ์ด๊ธฐํ
distance = [INF] * (n + 1)
# ๋ชจ๋ ๊ฐ์ ์ ๋ณด ์
๋ ฅ๋ฐ๊ธฐ
for _ in range(m):
# a ๋
ธ๋์์ b ๋
ธ๋๋ก ๊ฐ๋ ๋น์ฉ์ด c
a, b, c = map(int,input().split())
graph[a].append((b,c))
def get_smallest_node():
min_value = INF
index = 0
for i in range(1, n+1):
if distance[i] < min_value and not visited[i]:
min_value = distance[i]
index = i
return index
def dijkstra(start):
distance[start] = 0
visited[start] = True
for node_info in graph[start]:
distance[node_info[0]] = node_info[1]
for i in range(n-1):
now = get_smallest_node()
visited[now] = True
for node_info in graph[now]:
cost = distance[now] + node_info[1]
if cost < distance[node_info[0]]:
distance[node_info[0]] = cost์ฐ์ ์์ํ(heapq) ๋ฅผ ์ด์ฉ
Last updated