Dijkstra's algoritme in Python & C++ (Voorbeeld)

⚡ Slimme samenvatting

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 Maps-routering, OSPF IP-routering en talloze toepassingen voor het vinden van het kortste pad in netwerken.

  • 🎯 Kernidee: Dijkstra's Algorithm greedily expands the closest unvisited vertex, updating neighbor distances until every reachable node holds its true shortest cost from the source.
  • 🔄 Versus BFS en DFS: BFS en DFS vinden elk pad zonder rekening te houden met de gewichten van de randen, terwijl Dijkstra de totale kosten over gewogen randen minimaliseert.
  • 🧭 Stapsgewijs voorbeeld: Een uitgewerkte gewogen graaf met 7 knooppunten laat zien hoe afstanden iteratief worden bijgewerkt en hoe het pad 1-2-6-7 wint met een kosten van 7.
  • 💻 Taaldekking: Beiden C++ en Python Implementaties demonstreren de aangrenzingsmatrixversie met een selectiefunctie op basis van minimale afstand.
  • ⚠️ Beperking: Dijkstra schiet tekort bij negatieve randgewichten omdat een afgerond knooppunt nooit opnieuw wordt overwogen; gebruik Bellman-Ford voor grafieken met negatieve randen.
  • 📊 complexiteit: De naïeve array-versie werkt in O(V²) tijd en ruimte; een prioriteitswachtrij verlaagt de tijd tot O(E log V) voor dunne grafieken.

Dijkstra's kortste-pad-algoritme

Wat is het kortste pad of de kortste afstand?

Een pad van het bronknooppunt naar het bestemmingsknooppunt dat de kortste kosten met zich meebrengt, is het kortste pad of de kortste afstand. In de grafentheorie zijn er meerdere routes mogelijk van een bron naar een bestemming. Als er onder deze routes een route is die de minimale kosten met zich meebrengt, noemen we dat het kortste pad.

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:

Ongedirigeerde gewogen grafiek

Een ongerichte gewogen grafiek

  • 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.
  • Het pad tussen knooppunt 1 en knooppunt 2 wordt de rand genoemd.
  • "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:
Route of padKosten
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

Van de vier routes zien we dat de eerste route 7 kost. Dat is dus de kortste route qua kosten.

Kortste weg

Kortste weg

Hoe het algoritme van Dijkstra werkt

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 hebzuchtig algoritme.

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

Stap 1) Initialiseer het startknooppunt met kosten van 0 en de rest van de knooppunten met oneindige kosten.
Stap 2) Houd een array of lijst bij om te bewaren track van de bezochte knooppunten.
Stap 3) Werk de knooppuntkosten bij met de minimale kosten. Dit kan door de huidige kosten te vergelijken met de padkosten (zoals gedemonstreerd in het voorbeeldgedeelte).
Stap 4) Ga door met stap 3 totdat alle knooppunten bezocht zijn.

Nadat we al deze stappen hebben doorlopen, vinden we het pad dat het minst kost van bron naar bestemming.

Verschil tussen Dijkstra en BFS, DFS

Het belangrijkste verschil tussen Dijkstra en BFS-DFS is dat Dijkstra een algoritme is voor het vinden van het kortste pad, terwijl BFS en DFS algemene padzoekalgoritmen zijn. In de meeste gevallen houden BFS en DFS geen rekening met de kosten van de randen bij het vinden van het pad. Deze algoritmen kunnen dus niet garanderen dat het kortste pad wordt gevonden.

2D-rasterdemonstratie van hoe BFS werkt

2D-rasterdemonstratie BFS

Algoschets, met een BFS-demonstratie

This demonstration indicates that BFS only finds the path. However, it does not care about the path's weight. BFS (Breedte-eerste zoekopdracht) gaat ervan uit dat reizen van het ene knooppunt naar het andere knooppunt slechts 1 kost.

Laten we eens een voorbeeldgrafiek bekijken:

2D-rasterdemonstratie voorbeeldgrafiek

Hier vindt BFS een pad op niveau 2. BFS doorloopt de graaf in niveauvolgorde. Het gaat dus als volgt:

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

Stap 2) Markeer knooppunten 2, 3 en 4 als niveau 1 en bezoek de aangrenzende knooppunten. Het zal alle aangrenzende knooppunten blijven verkennen totdat het het bestemmingsknooppunt bereikt.

In DFS-termen zal het pad van 1 tot 7 als volgt worden doorlopen:

  • 1 → 2 → 3 → 7 (oorspronkelijke kosten 10, DFS-kosten 3)
  • 1 → 2 → 6 → 7 (oorspronkelijke kosten 7, DFS-kosten 3)
  • 1 → 3 → 7 (oorspronkelijke kosten 8, DFS-kosten 2)
  • 1 → 4 → 5 → 7 (oorspronkelijke kosten 13, DFS-kosten 3)

Zoals we zien, berekent DFS de padkosten aan de hand van het aantal randen. DFS doet het volgende:

  • DFS kan een pad vinden van de bron (beginpunt) naar de bestemming.
  • Het kan niet garanderen of het ontdekte pad van bronknooppunt naar bestemming het kortste pad is of niet.

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.

Voorbeeld van het algoritme van Dijkstra

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

Voorbeeld van het Dijkstra-algoritme

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.

Voor dit proces worden hieronder de stappen gegeven:

Stap 1) Initialiseer de startkosten van het knooppunt op 0. Wijs toe "Inf" naar de rest van de knooppunten. Dit betekent dat er geen pad bestaat tussen de bron en het knooppunt, of dat het pad nog niet is bezocht.

Initialisatie van het Dijkstra-algoritme

Stap 2) Wanneer je knooppunt 1 selecteert, wordt deze gemarkeerd als bezocht. Werk vervolgens alle aangrenzende buren van knooppunt 1 bij. 2, 3 en 4 zijn de buren van knooppunt 1.

Bij het bijwerken van kosten moeten we de onderstaande procedure volgen:

Updateprocedure van het Dijkstra-algoritme

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:

Dijkstra's algoritme na de eerste update

Stap 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.

Dijkstra's algoritme update knooppunt 6

Knooppunt 3 is een buur van knooppunt 2. We hebben echter de kosten ervan in de vorige stap berekend, namelijk 7. Als ons pad nu 1-2-3 is, heeft knooppunt 3 een kostprijs van 10. Pad 1-2- 3 kost 10, terwijl 1 tot 3 7 kost.

Stap 4) Voor knooppunt 3 is het buurknooppunt 7. Door de huidige waarde van knooppunt 7 te vergelijken met de padkosten (7+1) of 8, kunnen we de kosten van knooppunt 7 bijwerken naar 8. We vinden dus een pad van knooppunt 1 naar knooppunt 7, namelijk 1→3→7. De kosten hiervan zijn 8.

Stap 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:

Dijkstra's algoritme na stap 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:

Dijkstra's algoritme, eindgrafiek

De rand gemarkeerd met een zwarte lijn is ons kortste pad van 1 naar 7, en het kost ons 7.

Pseudo Code Het algoritme van Dijkstra

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++ Implementatie van het Dijkstra-algoritme

To implement Dijkstra's algorithm using C++Hier is de code:

#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);
}

Output:

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 Implementatie van het Dijkstra-algoritme

To implement Dijkstra's algorithm using PythonHier is de code:

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)

Output:

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

We kunnen zien dat het algoritme de kortste afstand vanaf het bronknooppunt berekent.

Toepassing van het Dijkstra-algoritme

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:

Dijkstra in Google Maps: Dit algoritme vormt de basis voor het vinden van de kortste paden, zoals we kunnen zien in de bovenstaande code-uitvoer.

Toepassing van het Dijkstra-algoritme Google Maps

Google Het maakt geen gebruik van het eenvoudige Dijkstra-algoritme. In plaats daarvan gebruikt het een aangepaste versie. Wanneer je een bestemming selecteert, toont het je meerdere routes in 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.

Dijkstra in IP-routering: IP-routering IP-routing is een netwerkterm. Het beschrijft hoe uw datapakket via verschillende paden naar de ontvanger wordt verzonden. Deze paden bestaan ​​uit routers, servers en andere apparatuur. Bij IP-routing worden verschillende protocollen gebruikt.

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.

Beperking van Dijkstra's algoritme

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

  • Er wordt één kortste pad genomen van het ene knooppunt naar het andere.
  • Zodra het kortste pad tussen twee knooppunten is geselecteerd, wordt dit niet opnieuw berekend.

Let hier op twee voorbeelden met negatieve randen.

Beperking van het Dijkstra-algoritme: negatieve randen

In de linker grafiek, Er zijn drie knooppunten. Dijkstra zal de grafiek als volgt analyseren:

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

Beperking van Dijkstra's algoritme, stap 1

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

Stap 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).

Stap 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.

Beperking van Dijkstra's algoritme, stap 4

Stap 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.

De complexiteit van het algoritme van 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 log V). Hier is E het aantal randen en V het aantal hoekpunten.

De ruimtelijke complexiteit is O(V²), omdat we een aangrenzende matrix gebruiken (2D-reeks). Ruimtecomplexiteit kan worden geoptimaliseerd met behulp van een aangrenzende lijst of wachtrijgegevensstructuur.

Veelgestelde vragen

AI-padplanningsagenten in robotica, autonome voertuigen en NPC's in games gebruiken het algoritme van Dijkstra om de goedkoopste routes op gewogen grafieken te vinden. Reinforcement learning-omgevingen vertrouwen er ook op om optimale referentiepaden te berekenen voor beloningsdeling.ping en evaluatie.

Ja. AI-codeerassistenten zoals GitHub Copilot en GPT kunnen het Dijkstra-algoritme genereren. Python, C++of JavaInclusief varianten met prioriteitswachtrijen die gebruikmaken van heaps. Ze kunnen ook het daadwerkelijke kortste pad afdrukken of de code aanpassen aan grafieken die zijn opgeslagen als aangrenzingslijsten.

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.

Dijkstra finaliseert een knooppunt zodra het de huidige minimale afstand heeft geselecteerd. Een latere negatieve kant zou een langer pad weliswaar goedkoper kunnen maken, maar het gefinaliseerde knooppunt wordt nooit meer bezocht, waardoor het algoritme een onjuiste kortste afstand rapporteert.

Kies Dijkstra wanneer elk randgewicht niet-negatief is, omdat deze methode sneller is met een looptijd van O((V+E) log V). Kies Bellman-Ford wanneer randen negatief kunnen zijn of wanneer je cycli met negatieve gewichten moet detecteren; de looptijd van O(V·E) is hiervoor een compromis.

Google Maps maakt gebruik van varianten en opvolgers van Dijkstra, waaronder A* en Con.tracHiërarchieën, afgestemd op wegennetwerken en actueel verkeer. Het onderliggende idee van gierige expansie door minimale geaccumuleerde kosten vormt nog steeds de kern van Dijkstra's bijdrage.

A* breidt Dijkstra uit door een heuristische schatting van de afstand tot het doel toe te voegen, waardoor minder knooppunten worden uitgebreid wanneer een goede heuristiek beschikbaar is. Dijkstra verkent in alle richtingen, terwijl A* de zoektocht naar het doel stuurt, waardoor het in de praktijk sneller is.

Dijkstra wordt niet alleen gebruikt voor kaarten, maar ook voor OSPF- en IS-IS-routeringsprotocollen op het internet, netwerktopologieoptimalisatie, telefoonroutering, bewegingsplanning voor robots, zoekopdrachten naar de kortste verbinding op sociale netwerken en kostenminimalisatie voor vliegreizen.

Vat dit bericht samen met: