다익스트라 알고리즘 Python & C++ (예)

⚡ 스마트 요약

Dijkstra's Algorithm computes the shortest path from a single source vertex to every other vertex in a weighted graph with non-negative edges. This greedy method underpins Google 지도 라우팅, OSPF IP 라우팅 및 수많은 네트워크 최단 경로 사용 사례.

  • 🎯 핵심 아이디어: Dijkstra's Algorithm greedily expands the closest unvisited vertex, updating neighbor distances until every reachable node holds its true shortest cost from the source.
  • 🔄 BFS 및 DFS 대비: BFS와 DFS는 간선 가중치를 고려하지 않고 모든 경로를 찾는 반면, 다익스트라 알고리즘은 가중치가 부여된 간선에 대한 총 비용을 최소화합니다.
  • 🧭 단계별 예: 7개의 정점을 가진 가중 그래프를 통해 거리가 어떻게 반복적으로 업데이트되는지, 그리고 경로 1-2-6-7이 비용 7로 가장 유리한 경로임을 보여줍니다.
  • 💻 언어 범위: 모두 C++ Python 구현 사례들은 최소 거리 선택 함수를 사용하는 인접 행렬 버전을 보여줍니다.
  • ⚠️ 한정: 다익스트라 알고리즘은 음수 간선 가중치를 가진 그래프에서는 실패합니다. 왜냐하면 확정된 노드가 다시 고려되지 않기 때문입니다. 음수 간선을 가진 그래프에는 벨만-포드 알고리즘을 사용하십시오.
  • 📊 복잡성: 단순한 배열 버전은 O(V²) 시간 및 공간 복잡도로 실행되지만, 우선순위 큐를 사용하면 희소 그래프의 경우 실행 시간이 O(E log V)로 줄어듭니다.

다익스트라 최단 경로 알고리즘

최단 경로 또는 최단 거리는 무엇입니까?

출발점에서 도착점까지 이동하는 데 드는 비용이 가장 적은 경로를 최단 경로 또는 최단 거리라고 합니다. 그래프 이론에서는 출발점에서 도착점까지 여러 경로가 존재할 수 있습니다. 이러한 경로들 중에서 비용이 가장 적은 경로가 있다면, 그 경로를 최단 경로라고 부릅니다.

Here "cost" means the number of nodes in the route or the summation of costs on each edge. A path can have one or multiple edges. The connection between two vertices is called an "edge". There are various types of shortest path algorithms, such as Dijkstra's Algorithm and the Bellman-Ford Algorithm.

Here, we discuss Dijkstra's Algorithm. Let us look at the following weighted graph:

무방향 가중 그래프

무방향 가중치 그래프

  • The term "weighted" means the cost of moving from one node to another. For example, moving from node 1 to node 2, the cost or weight is 1.
  • 노드 1과 노드 2 사이의 경로를 간선이라고 합니다.
  • "Undirected" means you can move from one node to another and back to the previous node. So, if we try to find all the routes from node 1 to node 7, they will be:
경로 또는 경로비용
1-2-6-7 로 문의하시기 바랍니다(1+3+3) = 7
1-2-3-7 로 문의하시기 바랍니다(1+9+1) = 11
1-3-7(7+1) = 8
1-4-5-7 로 문의하시기 바랍니다(6+2+5) = 13

이 네 가지 경로 중에서 첫 번째 경로의 비용이 7임을 알 수 있습니다. 따라서 비용 측면에서 가장 짧은 경로입니다.

최단 경로

최단 경로

Dijkstra 알고리즘의 작동 방식

Dijkstra's Algorithm can find the shortest distance in both directed and undirected weighted graphs. This algorithm is greedy because it always chooses the shortest or closest node from the origin. The term "greedy" means that among a set of outcomes or results, the algorithm will choose the best of them.

Here, we are trying to find the shortest paths among all other routes. So, Dijkstra's Algorithm finds all the shortest paths from a single source node. As a result, it behaves like a 탐욕스러운 알고리즘.

In the "example" section below, you will see the step-by-step approach. It works as follows:

단계 1) 시작 노드의 비용을 0으로 초기화하고 나머지 노드의 비용은 무한대로 설정합니다.
단계 2) 배열이나 리스트를 유지하여 관리하세요. trac방문한 노드의 k개.
단계 3) 노드 비용을 최소 비용으로 업데이트합니다. 이는 현재 비용과 경로 비용을 비교하여 수행할 수 있습니다(예제 섹션 참조).
단계 4) 모든 노드를 방문할 때까지 3단계를 계속하십시오.

이 모든 단계를 완료하면 소스에서 대상까지 최소 비용이 드는 경로를 찾을 수 있습니다.

Dijkstra와 BFS, DFS의 차이점

다익스트라 알고리즘과 BFS-DFS의 주요 차이점은 다익스트라는 최단 경로 탐색 알고리즘인 반면, BFS와 DFS는 일반적인 경로 탐색 알고리즘이라는 점입니다. 일반적으로 BFS와 DFS는 경로를 찾을 때 간선 비용을 고려하지 않습니다. 따라서 이러한 알고리즘은 최단 경로를 보장할 수 없습니다.

BFS 작동 방식을 보여주는 2D 그리드 데모

2D 그리드 데모 BFS

알고스케치, BFS 데모를 보여줍니다

This demonstration indicates that BFS only finds the path. However, it does not care about the path's weight. BFS (폭 우선 검색)는 한 노드에서 다른 노드로 이동하는 데 드는 비용은 1이라고 가정합니다.

예시 그래프를 살펴보겠습니다.

2D 그리드 데모 예시 그래프

여기서 BFS는 레벨 2에서 경로를 찾습니다. BFS는 그래프를 레벨 순서대로 탐색합니다. 따라서 다음과 같이 이동합니다.

단계 1) Start from node "1" and visit all the adjacent nodes 2, 3, 4.

단계 2) 노드 2, 3, 4를 레벨 1로 표시하고 인접한 노드들을 방문하세요. 그러면 목적지 노드에 도달할 때까지 모든 인접 노드를 계속 탐색합니다.

DFS 관점에서 보면 1부터 7까지의 경로는 다음과 같습니다.

  • 1→2→3→7 (원가 10, DFS 비용 3)
  • 1→2→6→7 (원가 7, DFS 비용 3)
  • 1→3→7 (원가 8, DFS 비용 2)
  • 1→4→5→7 (원가 13, DFS 비용 3)

보시다시피, DFS는 간선의 수를 이용하여 경로 비용을 계산합니다. DFS는 다음과 같은 과정을 거칩니다.

  • DFS는 소스(시작 정점)에서 대상까지의 경로를 찾을 수 있습니다.
  • 원본 노드에서 대상까지 검색된 경로가 최단 경로인지 여부는 보장할 수 없습니다.

However, in terms of Dijkstra's Algorithm, it chooses edges based on their cost. As a greedy algorithm, it will pick the minimum cost paths.

Dijkstra 알고리즘의 예

Dijkstra's Algorithm uses the cost or weight to calculate the total cost of the path.

다익스트라 알고리즘 예시

The target of Dijkstra's Algorithm is to minimize this total cost or weight. In the example shown above, we find the best paths from node 1 to node 7, then calculate all the costs.

In Dijkstra's Algorithm, it will find the shortest paths by calculating weights. It will not search for all possible paths. Let us demonstrate Dijkstra's Algorithm with an example. For example, you have been asked to find the shortest path from node 1 to 7.

이 프로세스의 단계는 다음과 같습니다.

단계 1) 시작 노드 비용을 0으로 초기화합니다. 할당합니다. "Inf" 나머지 노드로 이동합니다. 이는 출발지와 해당 노드 사이에 경로가 존재하지 않거나, 아직 해당 경로를 방문하지 않았음을 의미합니다.

다익스트라 알고리즘 초기화

단계 2) 노드 1을 선택하면 방문한 것으로 표시됩니다. 그런 다음 노드 1의 모든 인접 노드를 업데이트합니다. 2, 3, 4는 노드 1의 인접 노드입니다.

비용을 업데이트하는 동안 아래 절차를 따라야 합니다.

다익스트라 알고리즘 업데이트 절차

We can update each node's cost using the above formula. For example, we were at node 1, and we needed to update the cost of its adjacent nodes 2, 3, 4. After updating, the costs will look like this:

첫 번째 업데이트 후 다익스트라 알고리즘

단계 3) For node "2", neighbors are 6 and 3. We are updating the cost at "6" by comparing infinity (current value) with the cost of node 2 + path cost from 2 to 6. Simply put, node "6" will have the cost of 1+3 or 4.

다익스트라 알고리즘 업데이트 노드 6

노드 3은 노드 2의 이웃입니다. 그러나 이전 단계에서 비용을 계산했는데 7이었습니다. 이제 경로가 1-2-3이면 노드 3의 비용은 10이 됩니다. 경로 1-2- 3개는 10, 1~3개는 7개입니다.

단계 4) 노드 3의 경우, 가장 가까운 노드는 7입니다. 따라서 노드 7의 현재 값을 경로 비용(7+1) 또는 8과 비교하여 노드 7의 비용을 업데이트합니다. 즉, 8이 됩니다. 따라서 노드 1에서 노드 7로 가는 경로는 1→3→7이며, 비용은 8입니다.

단계 5) For node 4, we will update its adjacent node cost accordingly. So, node "5" will have an updated cost of 8. After step 4 and 5, it will look like this:

4단계 이후 다익스트라 알고리즘 5

Now, the path 1-3-7 has the cost of 8 (previously). Node "7" was not marked visited because we can reach node "7" from node "6". The path "1-2-6" had a cost of 4. So the path 1-2-6-7 will have the cost of 7.

As 7 < 8, the shortest path from source vertex "1" to destination vertex "7" will be 1-2-6-7, and the cost is 7. Previously it was 1-3-7, and the cost was 8. So, the final graph will look like this:

다익스트라 알고리즘 최종 그래프

검은색 선으로 표시된 가장자리는 1에서 7까지의 최단 경로이며 비용은 7입니다.

별명 Code 다익스트라 알고리즘

Here is the pseudo-code for Dijkstra's Algorithm:

Dijkstra(G, S):
  for each vertex V in G
    distance[V] <- Infinity
    previous[V] <- NULL
    if V does not equal S, then,
      (priority queue) Q.push(V)
  distance[S] = 0
  While Q is not empty
    U <- Extract the MIN from Q
    For each unvisited adjacent V of U
      TotalDistance <- distance[U] + edge_cost(U, V)
      if TotalDistance is less than distance[V], then
        distance[V] <- TotalDistance
        previous[V] <- U
  return distance, previous

C++ 다익스트라 알고리즘 구현

To implement Dijkstra's algorithm using C++다음은 코드입니다:

#include <bits/stdc++.h>
using namespace std;
#define size 7
int minimumDistance(int distance[], bool visited[]) {
  int min = INT_MAX;
  int min_index = INT_MAX;
  for (int i = 0; i < size; i++) {
    if (!visited[i] && distance[i] <= min) {
      min = distance[i];
      min_index = i;
    }
  }
  return min_index;
}
void printParentPath(int parent[], int i) {
  if (parent[i] == -1) {
    return;
  }
  printParentPath(parent, parent[i]);
  cout << i + 1 << " ";
}
void dijkstra(int graph[size][size], int source) {
  int distance[size];
  bool visited[size];
  int parent[size];
  for (int i = 0; i < size; i++) {
    parent[0] = -1;
    distance[i] = INT_MAX;
    visited[i] = false;
  }
  distance[source] = 0;
  for (int i = 0; i < size - 1; i++) {
    int U = minimumDistance(distance, visited);
    visited[U] = true;
    for (int j = 0; j < size; j++) {
      int curr_distance = distance[U] + graph[U][j];
      if (!visited[j] && graph[U][j] &&
          curr_distance < distance[j]) {
        parent[j] = U;
        distance[j] = curr_distance;
      }
    }
  }
  cout << "Vertex\t\tDistance\tPath" << endl;
  for (int i = 1; i < size; i++) {
    cout << source + 1 << "->" << i + 1 << "\t\t" << distance[i] << "\t\t"
         << source + 1 << " ";
    printParentPath(parent, i);
    cout << endl;
  }
}
int main() {
  int graph[size][size] = {{0, 1, 7, 6, 0, 0, 0}, {1, 0, 9, 0, 0, 3, 0},
                           {7, 9, 0, 0, 0, 0, 1}, {6, 0, 0, 0, 2, 0, 0},
                           {0, 0, 0, 2, 0, 0, 0}, {0, 3, 0, 0, 0, 0, 3},
                           {0, 0, 0, 0, 5, 3, 0}};
  dijkstra(graph, 0);
}

출력:

Vertex     Distance        Path

1->2           1             1 2
1->3           7             1 3
1->4           6             1 4
1->5           8             1 4 5
1->6           4             1 2 6
1->7           7             1 2 6 7

Python 다익스트라 알고리즘 구현

To implement Dijkstra's algorithm using Python다음은 코드입니다:

num_of_vertex = 7
def minimumDistance(distance, visited):
    _min = 1e11
    min_index = 1e11
    for i in range(num_of_vertex):
        if not visited[i] and distance[i] <= _min:
            _min = distance[i]
            min_index = i
    return min_index

def printParentNode(parent, i):
    if parent[i] == -1:
        return
    printParentNode(parent, parent[i])
    print("{} ".format(i + 1), end="")

def dijkstra(graph, src):
    distance = list()
    visited = list()
    parent = list()
    for i in range(num_of_vertex):
        parent.append(-1)
        distance.append(1e11)
        visited.append(False)
    distance[src] = 0
    for i in range(num_of_vertex - 1):
        U = minimumDistance(distance, visited)
        visited[U] = True
        for j in range(num_of_vertex):
            curr_distance = distance[U] + graph[U][j]
            if not visited[j] and graph[U][j] and curr_distance < distance[j]:
                parent[j] = U
                distance[j] = curr_distance
    print("Vertex\t\tDistance\tPath")
    for i in range(num_of_vertex):
        print("{}->{}\t\t{}\t\t{} ".format(src + 1, i + 1, distance[i], src + 1), end="")
        printParentNode(parent, i)
        print("")

graph = [
    [0, 1, 7, 6, 0, 0, 0],
    [1, 0, 9, 0, 0, 3, 0],
    [7, 9, 0, 0, 0, 0, 1],
    [6, 0, 0, 0, 2, 0, 0],
    [0, 0, 0, 2, 0, 0, 0],
    [0, 3, 0, 0, 0, 0, 3],
    [0, 0, 0, 0, 5, 3, 0]
]
dijkstra(graph, 0)

출력:

Vertex     Distance        Path

1->1           0              1
1->2           1              1 2
1->3           7              1 3
1->4           6              1 4
1->5           8              1 4 5
1->6           4              1 2 6
1->7           7              1 2 6 7

알고리즘이 출발 노드에서 최단 거리를 계산하는 것을 알 수 있습니다.

Dijkstra 알고리즘의 응용

Dijkstra's Algorithm has a large set of uses. Among those, it is widely used in the field of networking. Here are some real-life uses of Dijkstra's Algorithm:

다익스트라 인 Google 지도 : 위 코드 조각 출력에서 ​​볼 수 있듯이, 이 알고리즘은 최단 경로를 찾는 데 핵심적인 역할을 합니다.

Dijkstra 알고리즘의 응용 Google 지도

Google 단순 다익스트라 알고리즘을 사용하지 않고, 수정된 버전을 사용합니다. 목적지를 선택하면 여러 경로를 보여줍니다. Google Maps. Among these paths, some are sorted out for the user. These paths are selected based on "time". So, "time" is an edge cost for the shortest path.

IP 라우팅에서의 다익스트라 정리: IP 라우팅 라우팅은 네트워킹 용어입니다. 데이터 패킷이 여러 경로를 거쳐 수신자에게 전송되는 방식을 설명합니다. 이러한 경로는 라우터, 서버 및 기타 장비로 구성됩니다. IP 라우팅에는 다양한 유형의 프로토콜이 있습니다.

These protocols help the router find the shortest paths to send the data. One of the protocol names is "OSPF (Open Shortest Path First)". OSPF uses Dijkstra's algorithm. The router maintains a table of routes. Each router shares its table with neighbor routers. After receiving the updated table, they must calculate all the paths again. At that time, the router uses Dijkstra's Algorithm.

Dijkstra 알고리즘의 한계

Dijkstra's algorithm cannot guarantee the shortest path in a graph with negative edges. Dijkstra's algorithm follows these principles:

  • 한 노드에서 다른 노드로 하나의 최단 경로가 선택됩니다.
  • 두 노드 사이의 최단 경로가 선택되면 다시 계산되지 않습니다.

여기에서 음수 모서리가 있는 두 가지 예를 확인하세요.

다익스트라 알고리즘의 한계점: 음의 간선

왼쪽 그래프에서, 그래프에는 세 개의 정점이 있습니다. 다익스트라 알고리즘은 다음과 같이 실행됩니다.

단계 1) Starting vertex "1" will be initialized to zero. The other nodes will have infinity.

다익스트라 알고리즘 1단계의 한계

단계 2) Mark node "1" as visited and include it in the shortest path.

단계 3) The distance of the source node 1 to nodes "2" and "3" is set to infinity, as the shortest path is yet to be calculated. So, any path that costs less than infinity will be added to the shortest path (greedy approach).

단계 4) Updating the distance from source vertex "1" to "2". The current weight will be 5 (5 < infinity). Similarly, update the distance from node "1" to "3" with the weight of 3.

다익스트라 알고리즘 4단계의 한계

단계 5) Now if we check the shortest distances from node "1", we find that 5 is the shortest distance for edge 1→2. So, node "2" will be marked as visited. Similarly, node "3" will also be marked as visited as the shortest distance is 3.

However, if we observe, there is a path 1-3-2 that will cost only 2. But Dijkstra shows that from node "1" to node "2", the shortest distance is 5. So, Dijkstra failed to calculate the shortest distance correctly. The reason is that Dijkstra is a greedy algorithm. So, once a node is marked visited, it will not be reconsidered, although there might be a shorter path available. This issue only occurs when the edges have negative costs or negative weight edges.

Dijkstra fails to calculate the shortest path between two nodes in this scenario. As a result, this algorithm has some drawbacks. To solve this negative edge problem, another algorithm called the "Bellman-Ford Algorithm" is used. That algorithm can work with negative edges.

Dijkstra의 알고리즘 복잡도

The implementation above used two "for" loops. These loops run for the number of vertices. So, the time complexity is O(V²). Here, the term "O" is a notation that gives an assumption for the Dijkstra algorithm.

We can store the graph using a "priority queue". A priority queue is a binary heap data structure. It will be more efficient than a 2D matrix. An edge with a minimum cost will have a high priority. Then the time complexity will be O(E 로그 V). 여기서 E는 변의 개수이고, V는 꼭지점의 개수이다.

공간 복잡도는 O(V²), 인접 행렬(2D 배열). 공간 복잡도는 인접 리스트나 큐 데이터 구조를 사용하여 최적화할 수 있습니다.

자주 묻는 질문

로봇공학, 자율 주행 차량 및 게임 NPC에 사용되는 AI 경로 계획 에이전트는 가중 그래프에서 최저 비용 경로를 찾기 위해 다익스트라 알고리즘을 사용합니다. 강화 학습 환경 또한 보상 체계에 대한 최적의 참조 경로를 계산하기 위해 다익스트라 알고리즘에 의존합니다.ping 그리고 평가.

네. GitHub Copilot이나 GPT 같은 AI 코딩 도우미는 다익스트라 알고리즘을 생성할 수 있습니다. Python, C++및 Java힙을 사용하는 우선순위 큐 변형을 포함하여 다양한 방식을 지원합니다. 또한 실제 최단 경로를 출력하거나 인접 리스트로 저장된 그래프에 맞게 코드를 조정할 수도 있습니다.

Using a simple array to find the minimum node, Dijkstra's Algorithm runs in O(V²) time. With a binary heap priority queue it drops to O((V + E) log V), and with a Fibonacci heap it reaches O(E + V log V), best for sparse graphs.

다익스트라 알고리즘은 현재 최소 거리를 선택하는 즉시 정점을 확정합니다. 나중에 음의 간선이 추가되어 더 긴 경로가 더 저렴해질 수 있지만, 확정된 정점은 다시 방문되지 않으므로 알고리즘은 잘못된 최단 거리를 보고합니다.

모든 간선 가중치가 음수가 아닌 경우에는 O((V+E) log V)의 빠른 실행 시간을 갖는 다익스트라 알고리즘을 선택하십시오. 간선 가중치가 음수일 수 있거나 음수 가중치 사이클을 감지해야 하는 경우에는 O(V·E)의 실행 시간을 갖는 벨만-포드 알고리즘을 선택하십시오.

Google Maps는 A* 및 Con을 포함한 다익스트라 알고리즘의 변형 및 후속 버전을 사용합니다.trac도로망과 실제 교통 상황에 맞춰 조정된 계층 구조. 최소 누적 비용을 통한 탐욕적 확장이라는 기본 아이디어는 여전히 다익스트라의 핵심 공헌입니다.

A* 알고리즘은 목표까지의 거리를 추정하는 휴리스틱을 추가하여 다익스트라 알고리즘을 확장한 것입니다. 좋은 휴리스틱을 사용할 수 있을 경우 탐색 노드 수를 줄입니다. 다익스트라 알고리즘은 모든 방향으로 탐색하는 반면, A* 알고리즘은 목표 방향으로 탐색을 집중시켜 실제 계산 속도를 높입니다.

지도 외에도 다익스트라 알고리즘은 인터넷상의 OSPF 및 IS-IS 라우팅 프로토콜, 네트워크 토폴로지 최적화, 전화 통화 라우팅, 로봇 동작 계획, 소셜 네트워크 최단 연결 검색, 항공편 비용 최소화 등에 활용됩니다.

이 게시물을 요약하면 다음과 같습니다.