다익스트라 알고리즘 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 라우팅 및 수많은 네트워크 최단 경로 사용 사례.

최단 경로 또는 최단 거리는 무엇입니까?
출발점에서 도착점까지 이동하는 데 드는 비용이 가장 적은 경로를 최단 경로 또는 최단 거리라고 합니다. 그래프 이론에서는 출발점에서 도착점까지 여러 경로가 존재할 수 있습니다. 이러한 경로들 중에서 비용이 가장 적은 경로가 있다면, 그 경로를 최단 경로라고 부릅니다.
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 그리드 데모
알고스케치, BFS 데모를 보여줍니다
This demonstration indicates that BFS only finds the path. However, it does not care about the path's weight. BFS (폭 우선 검색)는 한 노드에서 다른 노드로 이동하는 데 드는 비용은 1이라고 가정합니다.
예시 그래프를 살펴보겠습니다.
여기서 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.
노드 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:
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 지도 : 위 코드 조각 출력에서 볼 수 있듯이, 이 알고리즘은 최단 경로를 찾는 데 핵심적인 역할을 합니다.
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.
단계 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.
단계 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 배열). 공간 복잡도는 인접 리스트나 큐 데이터 구조를 사용하여 최적화할 수 있습니다.















