📙
python-algorithm
  • 🖋️알고리즘 풀이 저장소
  • 이론
    • BFS & DFS 이론
    • 다익스트라 이론
    • 최소신장트리(크루스칼) 이론
    • 백트래킹 이론
  • 유형
    • 정렬
    • 순열과 조합
    • 탐색
    • 이분 탐색
    • SHA-256
    • 투 포인터
    • 피보나치
    • Z 재귀함수
    • 재귀함수
    • 친구 네트워크
    • 찾기
    • 큐
    • 스택 수열
    • 기하학
    • 트리 순회
    • 고급 탐색
    • BFS & DFS 알고리즘
    • 다익스트라 알고리즘
    • 최소신장트리(크루스칼) 알고리즘
    • 동적 프로그래밍
    • 그리디 알고리즘
    • 백트래킹 알고리즘
  • 기타
    • 베스트셀러
    • 성
    • 키 로거
    • 음계
Powered by GitBook
On this page
  • 최단경로 구하기
  • 다익스트라 알고리즘을 사용하여 (단방향)최단경로 구하기
  1. 이론

다익스트라 이론

PreviousBFS & DFS 이론Next최소신장트리(크루스칼) 이론

Last updated 3 years ago

최단경로 구하기

다익스트라 알고리즘을 사용하여 (단방향)최단경로 구하기

dijkstra-graph

위와 같은 그래프에서 최단경로 구하기(모든 방향은 단방향)

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_node로 가는데 걸리는 길이가 current_distance
        current_distance, current_node = heapq.heappop(queue)
        
        if distances[current_node] < current_distance:
            continue
            
        for adjacent, weight in graph[current_node].items():
            # distance = current_node로 가는데 걸리는 길이 + (근접한 다른)adjacent 노드로 가는데 걸리는 길이
            distance = current_distance + weight
            
            # 위에서 계산한 distance와 기존 distance를 비교
            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}
}

dijkstra(mygraph, 'A')