Алгоритм Дейкстри в 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 Маршрутизація на картах, маршрутизація IP OSPF та безліч варіантів використання найкоротших шляхів у мережі.

  • 🎯 Основна ідея: 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'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) Зберігати масив або список для зберігання track відвіданих вузлів.
Крок 3) Оновіть вартість вузла, встановивши мінімальну вартість. Це можна зробити, порівнявши поточну вартість з вартістю шляху (продемонстровано в розділі прикладів).
Крок 4) Продовжуйте крок 3, доки не будуть відвідані всі вузли.

Після виконання всіх цих кроків ми знайдемо мінімальний шлях від джерела до пункту призначення.

Різниця між Дейкстрою та BFS, DFS

Основна відмінність між алгоритмом Дейкстри та BFS-DFS полягає в тому, що Дейкстра є алгоритмом пошуку найкоротшого шляху, тоді як BFS та DFS є загальними алгоритмами пошуку шляху. У загальних випадках BFS та DFS не враховують вартість ребра під час пошуку шляху. Отже, ці алгоритми не можуть гарантувати найкоротший шлях.

Демонстрація двовимірної сітки принципу роботи BFS

Демонстрація 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'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'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 не використовує простий алгоритм Дейкстри. Натомість він використовує модифіковану версію. Коли ви вибираєте пункт призначення, він показує вам кілька шляхів у 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'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.

Складність алгоритму Дейкстри

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 log V). Тут E — кількість ребер, а V — кількість вершин.

Космічна складність є O(V²), оскільки ми використовуємо матрицю суміжності (2D масив). Складність простору можна оптимізувати за допомогою списку суміжності або структури даних черги.

Поширені запитання

Агенти планування шляхів на основі штучного інтелекту в робототехніці, автономних транспортних засобах та ігрових NPC використовують алгоритм Дейкстри для пошуку маршрутів з найнижчою вартістю на зважених графах. Середовища навчання з підкріпленням також покладаються на нього для обчислення оптимальних опорних шляхів для розподілу винагород.ping та оцінка.

Так. Помічники кодування на основі штучного інтелекту, такі як GitHub Copilot та GPT, можуть генерувати алгоритм Дейкстри в 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 У Картах використовуються варіанти та наступники Дейкстри, включаючи A* та ContracІєрархії, налаштовані на дорожні мережі та реальний трафік. Основна ідея жадібного розширення шляхом мінімальних накопичених витрат залишається основним внеском Дейкстри.

A* розширює метод Дейкстри, додаючи евристичну оцінку відстані до цілі, розширюючи меншу кількість вузлів, коли доступна хороша евристика. Дейкстра досліджує в усіх напрямках, тоді як A* зміщує пошук у напрямку до цілі, що робить його швидшим на практиці.

Окрім карт, Dijkstra забезпечує протоколи маршрутизації OSPF та IS-IS в Інтернеті, оптимізацію топології мережі, маршрутизацію телефонних дзвінків, планування руху робототехніки, запити найкоротших з'єднань у соціальних мережах та мінімізацію вартості перельотів авіакомпаній.

Підсумуйте цей пост за допомогою: