February 14, 2021
동작 과정
int(1e9)
으로 초기화import sys
input = sys.stdin.readline
INF = int(1e9)
n, m = map(int, input().split()) # 노드, 간선의 수
initial_node = int(input()) # 출발 노드 번호
graph = [[] for i in range(n + 1)]
visited = [False] * (n + 1)
distances = [INF] * (n + 1)
for _ in range(m):
a, b, c = map(int, input().split()) # c: a와 b 사이의 거리
graph[a].append((b, c))
def get_node_with_shortest_distance():
min_value = INF
index = 0 # 가장 최단 거리가 짧은 노드
for i in range(1, n + 1):
if distances[i] < min_value and not visited[i]:
min_value = distances[i]
index = i
return index
def dijkstra(initial_node):
distances[initial_node] = 0
visited[initial_node] = True
for j in graph[initial_node]:
distances[j[0]] = j[1]
for i in range(n - 1):
current_node = get_node_with_shortest_distance()
visited[current_node] = True
for j in graph[current_node]:
distance = distances[current_node] + j[1]
if distance < distances[j[0]]:
distances[j[0]] = distance
dijkstra(initial_node)
for i in range(1, n + 1):
if distances[i] == INF:
print("INFINITY")
else:
print(distances[i])
6 11
1
1 2 2
1 3 5
1 4 1
2 3 3
2 4 2
3 2 3
3 6 5
4 3 3
4 5 1
5 3 1
5 6 2
0
2
3
1
2
4
힙 자료구조 사용 → 출발 노드로부터 가장 거리가 짧은 노드를 찾는데 로그 시간이 소요된다. (vs. 다익스트라 알고리즘: )
import heapq
import sys
input = sys.stdin.readline
INF = int(1e9)
n, m = map(int, input().split())
start = int(input())
graph = [[] for i in range(n + 1)]
distance = [INF] * (n + 1)
for _ in range(m):
a, b, c = map(int, input().split())
graph[a].append((b, c))
def dijkstra(start):
queue = []
heapq.heappush(queue, (0, start))
distance[start] = 0
while queue:
dist, now = heapq.heappop(queue)
if distance[now] < dist:
continue
for i in graph[now]:
cost = dist + i[1]
if cost < distance[i[0]]:
distance[i[0]] = cost
heapq.heappush(queue, (cost, i[0]))
dijkstra(start)
for i in range(1, n + 1):
if distance[i] == INF:
print("INFINITY")
else:
print(distance[i])
import heapq
def dijkstra(graph, start):
distances = {node: float('inf') for node in graph}
distances[start] = 0
queue = []
heapq.heappush(queue, [distances[start], start])
while queue:
current_distance, current_node = heapq.heappop(queue)
if distances[current_node] < current_distance:
continue
for adjacent, weight in graph[current_node].items():
distance = current_distance + weight
if distance < distances[adjacent]:
distances[adjacent] = distance
heapq.heappush(queue, [distance, adjacent])
return distances
mygraph = {
'A': {'B': 8, 'C': 1, 'D': 2},
'B': {},
'C': {'B': 5, 'D': 2},
'D': {'E': 3, 'F': 5},
'E': {'F': 1},
'F': {'A': 5}
}
print(dijkstra(mygraph, 'A'))
# Result: {'A': 0, 'B': 6, 'C': 1, 'D': 2, 'E': 5, 'F': 6}
Source