Gegeven een gewogen grafiek en een bronpunt in de grafiek, zoek dan de kortste paden van de bron naar alle andere hoekpunten in de gegeven grafiek.
Opmerking: De gegeven grafiek bevat geen negatieve rand.
Voorbeelden:
Aanbevolen praktijk Implementatie van het Dijkstra-algoritme Probeer het!Invoer: src = 0, de grafiek wordt hieronder weergegeven.
Uitgang: 0 4 12 19 21 11 9 8 14
Uitleg: De afstand van 0 tot 1 = 4.
De minimale afstand van 0 tot 2 = 12. 0->1->2
De minimale afstand van 0 tot 3 = 19. 0->1->2->3
De minimale afstand van 0 tot 4 = 21. 0->7->6->5->4
De minimale afstand van 0 tot 5 = 11. 0->7->6->5
De minimale afstand van 0 tot 6 = 9. 0->7->6
De minimale afstand van 0 tot 7 = 8. 0->7
De minimale afstand van 0 tot 8 = 14. 0->1->2->8
Het algoritme van Dijkstra gebruikt Nabijheidsmatrix :
Het idee is om een SPT (kortste padboom) met een bepaalde bron als root. Handhaaf een aangrenzende matrix met twee sets,
shweta tiwari-acteur
- één set bevat hoekpunten die zijn opgenomen in de boom met het kortste pad,
- een andere set bevat hoekpunten die nog niet zijn opgenomen in de kortstepadboom.
Zoek bij elke stap van het algoritme een hoekpunt dat zich in de andere set bevindt (set nog niet inbegrepen) en een minimale afstand tot de bron heeft.
Algoritme :
- Maak een set sptSet (kortste padboomset) die de hoekpunten bijhoudt die zijn opgenomen in de kortste padboom, d.w.z. waarvan de minimale afstand tot de bron wordt berekend en afgerond. In eerste instantie is deze set leeg.
- Wijs een afstandswaarde toe aan alle hoekpunten in de invoergrafiek. Initialiseer alle afstandswaarden als ONEINDIG . Wijs de afstandswaarde toe als 0 voor het bronpunt, zodat dit als eerste wordt gekozen.
- Terwijl sptSet omvat niet alle hoekpunten
- Kies een hoekpunt in dat zit er niet in sptSet en heeft een minimale afstandswaarde.
- Voeg u toe sptSet .
- Werk vervolgens de afstandswaarde van alle aangrenzende hoekpunten bij in .
- Om de afstandswaarden bij te werken, itereert u door alle aangrenzende hoekpunten.
- Voor elk aangrenzend hoekpunt in, als de som van de afstandswaarde van in (van bron) en gewicht van de rand u-v , is kleiner dan de afstandswaarde van in en update vervolgens de afstandswaarde van in .
Opmerking: We gebruiken een Booleaanse array sptSet[] om de verzameling hoekpunten weer te geven die erin zijn opgenomen SPT . Als een waarde sptSet[v] waar is, dan is hoekpunt v inbegrepen SPT , anders niet. Array afstand[] wordt gebruikt om de kortste afstandswaarden van alle hoekpunten op te slaan.
Illustratie van het Dijkstra-algoritme :
Om het algoritme van Dijkstra te begrijpen, kunnen we een grafiek nemen en het kortste pad van de bron naar alle knooppunten vinden.
machine learning-modellenBeschouw onderstaande grafiek en src = 0
Stap 1:
- De set sptSet is aanvankelijk leeg en de afstanden toegewezen aan hoekpunten zijn {0, INF, INF, INF, INF, INF, INF, INF} waarbij INF geeft oneindig aan.
- Kies nu het hoekpunt met een minimale afstandswaarde. Het hoekpunt 0 wordt gekozen, neem het op sptSet . Dus sptSet wordt {0}. Na het opnemen van 0 tot sptSet , update de afstandswaarden van de aangrenzende hoekpunten.
- Aangrenzende hoekpunten van 0 zijn 1 en 7. De afstandswaarden van 1 en 7 worden bijgewerkt als 4 en 8.
De volgende subgrafiek toont hoekpunten en hun afstandswaarden; alleen de hoekpunten met eindige afstandswaarden worden getoond. De hoekpunten die zijn opgenomen in SPT worden getoond groente kleur.
Stap 2:
- Kies het hoekpunt met de minimale afstandswaarde en nog niet opgenomen in SPT (niet in sptSET ). Het hoekpunt 1 wordt gekozen en toegevoegd sptSet .
- Dus sptSet wordt nu {0, 1}. Update de afstandswaarden van aangrenzende hoekpunten van 1.
- De afstandswaarde van hoekpunt 2 wordt 12 .
Stap 3:
- Kies het hoekpunt met de minimale afstandswaarde en nog niet opgenomen in SPT (niet in sptSET ). Vertex 7 wordt gekozen. Dus sptSet wordt nu {0, 1, 7}.
- Update de afstandswaarden van aangrenzende hoekpunten van 7. De afstandswaarde van hoekpunten 6 en 8 wordt eindig ( 15 en 9 respectievelijk).
Stap 4:
- Kies het hoekpunt met de minimale afstandswaarde en nog niet opgenomen in SPT (niet in sptSET ). Vertex 6 wordt gekozen. Dus sptSet wordt nu {0, 1, 7, 6} .
- Update de afstandswaarden van aangrenzende hoekpunten van 6. De afstandswaarde van hoekpunten 5 en 8 worden bijgewerkt.
We herhalen de bovenstaande stappen tot sptSet omvat alle hoekpunten van de gegeven grafiek. Tenslotte krijgen we de volgende S Horste Path Tree (SPT).
Hieronder vindt u de implementatie van de bovenstaande aanpak:
C++ // C++ program for Dijkstra's single source shortest path // algorithm. The program is for adjacency matrix // representation of the graph #include using namespace std; #include // Number of vertices in the graph #define V 9 // A utility function to find the vertex with minimum // distance value, from the set of vertices not yet included // in shortest path tree int minDistance(int dist[], bool sptSet[]) { // Initialize min value int min = INT_MAX, min_index; for (int v = 0; v < V; v++) if (sptSet[v] == false && dist[v] <= min) min = dist[v], min_index = v; return min_index; } // A utility function to print the constructed distance // array void printSolution(int dist[]) { cout << 'Vertex Distance from Source' << endl; for (int i = 0; i < V; i++) cout << i << ' ' << dist[i] << endl; } // Function that implements Dijkstra's single source // shortest path algorithm for a graph represented using // adjacency matrix representation void dijkstra(int graph[V][V], int src) { int dist[V]; // The output array. dist[i] will hold the // shortest // distance from src to i bool sptSet[V]; // sptSet[i] will be true if vertex i is // included in shortest // path tree or shortest distance from src to i is // finalized // Initialize all distances as INFINITE and stpSet[] as // false for (int i = 0; i < V; i++) dist[i] = INT_MAX, sptSet[i] = false; // Distance of source vertex from itself is always 0 dist[src] = 0; // Find shortest path for all vertices for (int count = 0; count < V - 1; count++) { // Pick the minimum distance vertex from the set of // vertices not yet processed. u is always equal to // src in the first iteration. int u = minDistance(dist, sptSet); // Mark the picked vertex as processed sptSet[u] = true; // Update dist value of the adjacent vertices of the // picked vertex. for (int v = 0; v < V; v++) // Update dist[v] only if is not in sptSet, // there is an edge from u to v, and total // weight of path from src to v through u is // smaller than current value of dist[v] if (!sptSet[v] && graph[u][v] && dist[u] != INT_MAX && dist[u] + graph[u][v] < dist[v]) dist[v] = dist[u] + graph[u][v]; } // print the constructed distance array printSolution(dist); } // driver's code int main() { /* Let us create the example graph discussed above */ int graph[V][V] = { { 0, 4, 0, 0, 0, 0, 0, 8, 0 }, { 4, 0, 8, 0, 0, 0, 0, 11, 0 }, { 0, 8, 0, 7, 0, 4, 0, 0, 2 }, { 0, 0, 7, 0, 9, 14, 0, 0, 0 }, { 0, 0, 0, 9, 0, 10, 0, 0, 0 }, { 0, 0, 4, 14, 10, 0, 2, 0, 0 }, { 0, 0, 0, 0, 0, 2, 0, 1, 6 }, { 8, 11, 0, 0, 0, 0, 1, 0, 7 }, { 0, 0, 2, 0, 0, 0, 6, 7, 0 } }; // Function call dijkstra(graph, 0); return 0; } // This code is contributed by shivanisinghss2110> C // C program for Dijkstra's single source shortest path // algorithm. The program is for adjacency matrix // representation of the graph #include #include #include // Number of vertices in the graph #define V 9 // A utility function to find the vertex with minimum // distance value, from the set of vertices not yet included // in shortest path tree int minDistance(int dist[], bool sptSet[]) { // Initialize min value int min = INT_MAX, min_index; for (int v = 0; v < V; v++) if (sptSet[v] == false && dist[v] <= min) min = dist[v], min_index = v; return min_index; } // A utility function to print the constructed distance // array void printSolution(int dist[]) { printf('Vertex Distance from Source
'); for (int i = 0; i < V; i++) printf('%d %d
', i, dist[i]); } // Function that implements Dijkstra's single source // shortest path algorithm for a graph represented using // adjacency matrix representation void dijkstra(int graph[V][V], int src) { int dist[V]; // The output array. dist[i] will hold the // shortest // distance from src to i bool sptSet[V]; // sptSet[i] will be true if vertex i is // included in shortest // path tree or shortest distance from src to i is // finalized // Initialize all distances as INFINITE and stpSet[] as // false for (int i = 0; i < V; i++) dist[i] = INT_MAX, sptSet[i] = false; // Distance of source vertex from itself is always 0 dist[src] = 0; // Find shortest path for all vertices for (int count = 0; count < V - 1; count++) { // Pick the minimum distance vertex from the set of // vertices not yet processed. u is always equal to // src in the first iteration. int u = minDistance(dist, sptSet); // Mark the picked vertex as processed sptSet[u] = true; // Update dist value of the adjacent vertices of the // picked vertex. for (int v = 0; v < V; v++) // Update dist[v] only if is not in sptSet, // there is an edge from u to v, and total // weight of path from src to v through u is // smaller than current value of dist[v] if (!sptSet[v] && graph[u][v] && dist[u] != INT_MAX && dist[u] + graph[u][v] < dist[v]) dist[v] = dist[u] + graph[u][v]; } // print the constructed distance array printSolution(dist); } // driver's code int main() { /* Let us create the example graph discussed above */ int graph[V][V] = { { 0, 4, 0, 0, 0, 0, 0, 8, 0 }, { 4, 0, 8, 0, 0, 0, 0, 11, 0 }, { 0, 8, 0, 7, 0, 4, 0, 0, 2 }, { 0, 0, 7, 0, 9, 14, 0, 0, 0 }, { 0, 0, 0, 9, 0, 10, 0, 0, 0 }, { 0, 0, 4, 14, 10, 0, 2, 0, 0 }, { 0, 0, 0, 0, 0, 2, 0, 1, 6 }, { 8, 11, 0, 0, 0, 0, 1, 0, 7 }, { 0, 0, 2, 0, 0, 0, 6, 7, 0 } }; // Function call dijkstra(graph, 0); return 0; }> Java // A Java program for Dijkstra's single source shortest path // algorithm. The program is for adjacency matrix // representation of the graph import java.io.*; import java.lang.*; import java.util.*; class ShortestPath { // A utility function to find the vertex with minimum // distance value, from the set of vertices not yet // included in shortest path tree static final int V = 9; int minDistance(int dist[], Boolean sptSet[]) { // Initialize min value int min = Integer.MAX_VALUE, min_index = -1; for (int v = 0; v < V; v++) if (sptSet[v] == false && dist[v] <= min) { min = dist[v]; min_index = v; } return min_index; } // A utility function to print the constructed distance // array void printSolution(int dist[]) { System.out.println( 'Vertex Distance from Source'); for (int i = 0; i < V; i++) System.out.println(i + ' ' + dist[i]); } // Function that implements Dijkstra's single source // shortest path algorithm for a graph represented using // adjacency matrix representation void dijkstra(int graph[][], int src) { int dist[] = new int[V]; // The output array. // dist[i] will hold // the shortest distance from src to i // sptSet[i] will true if vertex i is included in // shortest path tree or shortest distance from src // to i is finalized Boolean sptSet[] = new Boolean[V]; // Initialize all distances as INFINITE and stpSet[] // as false for (int i = 0; i < V; i++) { dist[i] = Integer.MAX_VALUE; sptSet[i] = false; } // Distance of source vertex from itself is always 0 dist[src] = 0; // Find shortest path for all vertices for (int count = 0; count < V - 1; count++) { // Pick the minimum distance vertex from the set // of vertices not yet processed. u is always // equal to src in first iteration. int u = minDistance(dist, sptSet); // Mark the picked vertex as processed sptSet[u] = true; // Update dist value of the adjacent vertices of // the picked vertex. for (int v = 0; v < V; v++) // Update dist[v] only if is not in sptSet, // there is an edge from u to v, and total // weight of path from src to v through u is // smaller than current value of dist[v] if (!sptSet[v] && graph[u][v] != 0 && dist[u] != Integer.MAX_VALUE && dist[u] + graph[u][v] < dist[v]) dist[v] = dist[u] + graph[u][v]; } // print the constructed distance array printSolution(dist); } // Driver's code public static void main(String[] args) { /* Let us create the example graph discussed above */ int graph[][] = new int[][] { { 0, 4, 0, 0, 0, 0, 0, 8, 0 }, { 4, 0, 8, 0, 0, 0, 0, 11, 0 }, { 0, 8, 0, 7, 0, 4, 0, 0, 2 }, { 0, 0, 7, 0, 9, 14, 0, 0, 0 }, { 0, 0, 0, 9, 0, 10, 0, 0, 0 }, { 0, 0, 4, 14, 10, 0, 2, 0, 0 }, { 0, 0, 0, 0, 0, 2, 0, 1, 6 }, { 8, 11, 0, 0, 0, 0, 1, 0, 7 }, { 0, 0, 2, 0, 0, 0, 6, 7, 0 } }; ShortestPath t = new ShortestPath(); // Function call t.dijkstra(graph, 0); } } // This code is contributed by Aakash Hasija> Python # Python program for Dijkstra's single # source shortest path algorithm. The program is # for adjacency matrix representation of the graph # Library for INT_MAX import sys class Graph(): def __init__(self, vertices): self.V = vertices self.graph = [[0 for column in range(vertices)] for row in range(vertices)] def printSolution(self, dist): print('Vertex Distance from Source') for node in range(self.V): print(node, ' ', dist[node]) # A utility function to find the vertex with # minimum distance value, from the set of vertices # not yet included in shortest path tree def minDistance(self, dist, sptSet): # Initialize minimum distance for next node min = sys.maxsize # Search not nearest vertex not in the # shortest path tree for u in range(self.V): if dist[u] < min and sptSet[u] == False: min = dist[u] min_index = u return min_index # Function that implements Dijkstra's single source # shortest path algorithm for a graph represented # using adjacency matrix representation def dijkstra(self, src): dist = [sys.maxsize] * self.V dist[src] = 0 sptSet = [False] * self.V for cout in range(self.V): # Pick the minimum distance vertex from # the set of vertices not yet processed. # x is always equal to src in first iteration x = self.minDistance(dist, sptSet) # Put the minimum distance vertex in the # shortest path tree sptSet[x] = True # Update dist value of the adjacent vertices # of the picked vertex only if the current # distance is greater than new distance and # the vertex in not in the shortest path tree for y in range(self.V): if self.graph[x][y]>0 en sptSet[y] == False en dist[y]> dist[x] + self.graph[x][y]: dist[y] = dist[x] + self.graph[x][y] self.printSolution(dist) # Stuurprogrammacode if __name__ == '__main__': g = Graph(9) g.graph = [[0, 4, 0, 0, 0, 0, 0, 8, 0], [4, 0, 8, 0, 0, 0, 0, 11, 0], [0, 8, 0, 7, 0, 4, 0, 0, 2], [0, 0, 7, 0, 9, 14, 0, 0, 0], [0, 0, 0, 9, 0, 10, 0, 0, 0], [0, 0, 4, 14, 10, 0, 2, 0, 0], [0, 0, 0, 0, 0, 2, 0, 1, 6], [8, 11, 0, 0, 0, 0, 1, 0, 7], [0, 0, 2, 0, 0, 0, 6, 7, 0] ] g.dijkstra(0) # Deze code is bijgedragen door Divyanshu Mehta en bijgewerkt door Pranav Singh Sambyal> C# // C# program for Dijkstra's single // source shortest path algorithm. // The program is for adjacency matrix // representation of the graph using System; class GFG { // A utility function to find the // vertex with minimum distance // value, from the set of vertices // not yet included in shortest // path tree static int V = 9; int minDistance(int[] dist, bool[] sptSet) { // Initialize min value int min = int.MaxValue, min_index = -1; for (int v = 0; v < V; v++) if (sptSet[v] == false && dist[v] <= min) { min = dist[v]; min_index = v; } return min_index; } // A utility function to print // the constructed distance array void printSolution(int[] dist) { Console.Write('Vertex Distance ' + 'from Source
'); for (int i = 0; i < V; i++) Console.Write(i + ' ' + dist[i] + '
'); } // Function that implements Dijkstra's // single source shortest path algorithm // for a graph represented using adjacency // matrix representation void dijkstra(int[, ] graph, int src) { int[] dist = new int[V]; // The output array. dist[i] // will hold the shortest // distance from src to i // sptSet[i] will true if vertex // i is included in shortest path // tree or shortest distance from // src to i is finalized bool[] sptSet = new bool[V]; // Initialize all distances as // INFINITE and stpSet[] as false for (int i = 0; i < V; i++) { dist[i] = int.MaxValue; sptSet[i] = false; } // Distance of source vertex // from itself is always 0 dist[src] = 0; // Find shortest path for all vertices for (int count = 0; count < V - 1; count++) { // Pick the minimum distance vertex // from the set of vertices not yet // processed. u is always equal to // src in first iteration. int u = minDistance(dist, sptSet); // Mark the picked vertex as processed sptSet[u] = true; // Update dist value of the adjacent // vertices of the picked vertex. for (int v = 0; v < V; v++) // Update dist[v] only if is not in // sptSet, there is an edge from u // to v, and total weight of path // from src to v through u is smaller // than current value of dist[v] if (!sptSet[v] && graph[u, v] != 0 && dist[u] != int.MaxValue && dist[u] + graph[u, v] < dist[v]) dist[v] = dist[u] + graph[u, v]; } // print the constructed distance array printSolution(dist); } // Driver's Code public static void Main() { /* Let us create the example graph discussed above */ int[, ] graph = new int[, ] { { 0, 4, 0, 0, 0, 0, 0, 8, 0 }, { 4, 0, 8, 0, 0, 0, 0, 11, 0 }, { 0, 8, 0, 7, 0, 4, 0, 0, 2 }, { 0, 0, 7, 0, 9, 14, 0, 0, 0 }, { 0, 0, 0, 9, 0, 10, 0, 0, 0 }, { 0, 0, 4, 14, 10, 0, 2, 0, 0 }, { 0, 0, 0, 0, 0, 2, 0, 1, 6 }, { 8, 11, 0, 0, 0, 0, 1, 0, 7 }, { 0, 0, 2, 0, 0, 0, 6, 7, 0 } }; GFG t = new GFG(); // Function call t.dijkstra(graph, 0); } } // This code is contributed by ChitraNayal> Javascript // A Javascript program for Dijkstra's single // source shortest path algorithm. // The program is for adjacency matrix // representation of the graph let V = 9; // A utility function to find the // vertex with minimum distance // value, from the set of vertices // not yet included in shortest // path tree function minDistance(dist,sptSet) { // Initialize min value let min = Number.MAX_VALUE; let min_index = -1; for(let v = 0; v < V; v++) { if (sptSet[v] == false && dist[v] <= min) { min = dist[v]; min_index = v; } } return min_index; } // A utility function to print // the constructed distance array function printSolution(dist) { console.log('Vertex Distance from Source '); for(let i = 0; i < V; i++) { console.log(i + ' ' + dist[i] + ' '); } } // Function that implements Dijkstra's // single source shortest path algorithm // for a graph represented using adjacency // matrix representation function dijkstra(graph, src) { let dist = new Array(V); let sptSet = new Array(V); // Initialize all distances as // INFINITE and stpSet[] as false for(let i = 0; i < V; i++) { dist[i] = Number.MAX_VALUE; sptSet[i] = false; } // Distance of source vertex // from itself is always 0 dist[src] = 0; // Find shortest path for all vertices for(let count = 0; count < V - 1; count++) { // Pick the minimum distance vertex // from the set of vertices not yet // processed. u is always equal to // src in first iteration. let u = minDistance(dist, sptSet); // Mark the picked vertex as processed sptSet[u] = true; // Update dist value of the adjacent // vertices of the picked vertex. for(let v = 0; v < V; v++) { // Update dist[v] only if is not in // sptSet, there is an edge from u // to v, and total weight of path // from src to v through u is smaller // than current value of dist[v] if (!sptSet[v] && graph[u][v] != 0 && dist[u] != Number.MAX_VALUE && dist[u] + graph[u][v] < dist[v]) { dist[v] = dist[u] + graph[u][v]; } } } // Print the constructed distance array printSolution(dist); } // Driver code let graph = [ [ 0, 4, 0, 0, 0, 0, 0, 8, 0 ], [ 4, 0, 8, 0, 0, 0, 0, 11, 0 ], [ 0, 8, 0, 7, 0, 4, 0, 0, 2 ], [ 0, 0, 7, 0, 9, 14, 0, 0, 0], [ 0, 0, 0, 9, 0, 10, 0, 0, 0 ], [ 0, 0, 4, 14, 10, 0, 2, 0, 0], [ 0, 0, 0, 0, 0, 2, 0, 1, 6 ], [ 8, 11, 0, 0, 0, 0, 1, 0, 7 ], [ 0, 0, 2, 0, 0, 0, 6, 7, 0 ] ] dijkstra(graph, 0); // This code is contributed by rag2127> Uitvoer
Vertex Distance from Source 0 0 1 4 2 12 3 19 4 21 5 11 6 9 7 8 8 14>
Tijdcomplexiteit: O(V2)
Hulpruimte: O(V)
Opmerkingen:
- De code berekent de kortste afstand, maar berekent niet de padinformatie. Maak een bovenliggende array, werk de bovenliggende array bij wanneer de afstand wordt bijgewerkt en gebruik deze om het kortste pad van de bron naar verschillende hoekpunten weer te geven.
- De tijd Complexiteit van de implementatie is O(V 2 ) . Als de invoer grafiek wordt weergegeven met behulp van een aangrenzende lijst , kan het worden teruggebracht tot O(E * log V) met behulp van een binaire heap. Alsjeblieft zie Dijkstra's algoritme voor representatie van aangrenzende lijsten voor meer details.
- Het algoritme van Dijkstra werkt niet voor grafieken met negatieve gewichtscycli.
Waarom falen de algoritmen van Dijkstra voor de grafieken met negatieve randen?
Het probleem met negatieve gewichten komt voort uit het feit dat het algoritme van Dijkstra ervan uitgaat dat zodra een knooppunt wordt toegevoegd aan de reeks bezochte knooppunten, de afstand ervan definitief is en niet zal veranderen. Bij aanwezigheid van negatieve gewichten kan deze aanname echter tot onjuiste resultaten leiden.
installeer maven
Bekijk de volgende grafiek voor het voorbeeld:

In de bovenstaande grafiek is A het bronknooppunt tussen de randen A naar B En A naar C , A naar B is het kleinere gewicht en Dijkstra kent de kortste afstand toe B als 2, maar vanwege het bestaan van een negatieve flank van C naar B , wordt de werkelijke kortste afstand teruggebracht tot 1, wat Dijkstra niet detecteert.
Opmerking: We gebruiken Het kortste pad-algoritme van Bellman Ford in het geval dat we negatieve randen in de grafiek hebben.
Kylie Jenner leeftijd
Het algoritme van Dijkstra gebruikt Nabijheidslijst in O(ElogV):
Voor het algoritme van Dijkstra wordt altijd aanbevolen om te gebruiken Telkens wanneer de afstand van een hoekpunt wordt verkleind, voegen we nog een exemplaar van een hoekpunt toe aan de prioriteitswachtrij. Zelfs als er meerdere instanties zijn, beschouwen we alleen de instantie met een minimale afstand en negeren we andere instanties.
De tijdscomplexiteit blijft bestaan O(E * LogV) aangezien er maximaal O(E)-hoekpunten in de prioriteitswachtrij zullen zijn en O(logE) hetzelfde is als O(logV)
Hieronder vindt u de implementatie van de bovenstaande aanpak:
C++ // C++ Program to find Dijkstra's shortest path using // priority_queue in STL #include using namespace std; #define INF 0x3f3f3f3f // iPair ==>Geheel getal Paar typedef paar iPair; // Deze klasse vertegenwoordigt een gerichte grafiek met behulp van // representatieklasse van aangrenzende lijst Graph { int V; // Aantal hoekpunten // In een gewogen grafiek moeten we hoekpunten // en een gewichtspaar opslaan voor elke lijst met randen>* bijvoeglijk naamwoord; publiek: Grafiek(int V); // Constructor // functie om een rand toe te voegen aan de grafiek void addEdge(int u, int v, int w); // drukt het kortste pad af van s void shortestPath(int s); }; // Wijst geheugen toe voor de aangrenzende lijst Graph::Graph(int V) { this->V = V; adj = nieuwe lijst [V]; } void Graph::addEdge(int u, int v, int w) { adj[u].push_back(make_pair(v, w)); adj[v].push_back(make_pair(u, w)); } // Drukt de kortste paden af van src naar alle andere hoekpunten void Graph::shortestPath(int src) {// Maak een prioriteitswachtrij om hoekpunten op te slaan die // worden voorbewerkt. Dit is een vreemde syntaxis in C++. // Zie onderstaande link voor details van deze syntaxis // https://www.techcodeview.com prioriteit_queue , groter > pq; // Maak een vector voor afstanden en initialiseer alle // afstanden als oneindige (INF) vector dist(V, INF); // Plaats de bron zelf in de prioriteitswachtrij en initialiseer // de afstand ervan als 0. pq.push(make_pair(0, src)); dist[src] = 0; /* Loopt totdat de prioriteitswachtrij leeg wordt (of alle afstanden zijn niet definitief) */ while (!pq.empty()) {/ // Het eerste hoekpunt in paar is de minimale afstand // hoekpunt, haal het uit de prioriteitswachtrij. // hoekpuntlabel wordt opgeslagen als seconde van een paar (het // moet op deze manier worden gedaan om de hoekpunten // gesorteerde afstand te behouden (afstand moet het eerste item zijn // in paar) int u = pq.top().second; pq.pop(); // 'i' wordt gebruikt om alle aangrenzende hoekpunten van een // hoekpuntenlijst op te halen>::iterator ik; for (i = adj[u].begin(); i != adj[u].end(); ++i) {// Haal het hoekpuntlabel op en het gewicht van de huidige // aangrenzend aan u. int v = (*i).eerste; int gewicht = (*i).seconde; // Als er een kort pad is naar v via u. if (dist[v]> dist[u] + gewicht) {// Afstand van v dist[v] = dist[u] + gewicht bijwerken; pq.push(make_pair(dist[v], v)); } } } // Print de kortste afstanden opgeslagen in dist[] printf('Vertex Distance from Source
'); voor (int i = 0; ik< V; ++i) printf('%d %d
', i, dist[i]); } // Driver's code int main() { // create the graph given in above figure int V = 9; Graph g(V); // making above shown graph g.addEdge(0, 1, 4); g.addEdge(0, 7, 8); g.addEdge(1, 2, 8); g.addEdge(1, 7, 11); g.addEdge(2, 3, 7); g.addEdge(2, 8, 2); g.addEdge(2, 5, 4); g.addEdge(3, 4, 9); g.addEdge(3, 5, 14); g.addEdge(4, 5, 10); g.addEdge(5, 6, 2); g.addEdge(6, 7, 1); g.addEdge(6, 8, 6); g.addEdge(7, 8, 7); // Function call g.shortestPath(0); return 0; }>
Java import java.util.*; class Graph { private int V; private List> bijvoeglijk naamwoord; Grafiek(int V) { dit.V = V; adj = nieuwe ArrayList(); voor (int i = 0; ik< V; i++) { adj.add(new ArrayList()); } } void addEdge(int u, int v, int w) { adj.get(u).add(new iPair(v, w)); adj.get(v).add(new iPair(u, w)); } void shortestPath(int src) { PriorityQueue pq = nieuwe PriorityQueue(V, Comparator.comparingInt(o -> o.second)); int[] dist = nieuwe int[V]; Arrays.fill(dist, Integer.MAX_VALUE); pq.add(nieuwe iPair(0, src)); dist[src] = 0; terwijl (!pq.isEmpty()) { int u = pq.poll().second; for (iPair v: adj.get(u)) { if (dist[v.first]> dist[u] + v.second) { dist[v.first] = dist[u] + v.second; pq.add(nieuwe iPair(dist[v.first], v.first)); } } } System.out.println('Vertexafstand vanaf bron'); voor (int i = 0; ik< V; i++) { System.out.println(i + ' ' + dist[i]); } } static class iPair { int first, second; iPair(int first, int second) { this.first = first; this.second = second; } } } public class Main { public static void main(String[] args) { int V = 9; Graph g = new Graph(V); g.addEdge(0, 1, 4); g.addEdge(0, 7, 8); g.addEdge(1, 2, 8); g.addEdge(1, 7, 11); g.addEdge(2, 3, 7); g.addEdge(2, 8, 2); g.addEdge(2, 5, 4); g.addEdge(3, 4, 9); g.addEdge(3, 5, 14); g.addEdge(4, 5, 10); g.addEdge(5, 6, 2); g.addEdge(6, 7, 1); g.addEdge(6, 8, 6); g.addEdge(7, 8, 7); g.shortestPath(0); } }>
Python import heapq # iPair ==>Integer Pair iPair = tuple # Deze klasse vertegenwoordigt een gerichte graaf met behulp van # representatieklasse van de aangrenzende lijst Grafiek: def __init__(self, V: int): # Constructor self.V = V self.adj = [[] voor _ in range(V )] def addEdge(self, u: int, v: int, w: int): self.adj[u].append((v, w)) self.adj[v].append((u, w)) # Drukt de kortste paden af van src naar alle andere hoekpunten def shortestPath(self, src: int): # Creëer een prioriteitswachtrij om hoekpunten op te slaan die # worden voorbewerkt pq = [] heapq.heappush(pq, (0, src)) # Maak een vector voor afstanden en initialiseer alle # afstanden als oneindig (INF) dist = [float('inf')] * self.V dist[src] = 0 terwijl pq: # Het eerste hoekpunt in paar is de minimale afstand # hoekpunt, extraheer het uit de prioriteitswachtrij. # hoekpuntlabel wordt opgeslagen in seconde van paar d, u = heapq.heappop(pq) # 'i' wordt gebruikt om alle aangrenzende hoekpunten van een # hoekpunt voor v te krijgen, gewicht in self.adj[u]: # If er is een kortgesloten pad naar v via u. if dist[v]> dist[u] + gewicht: # Updaten van de afstand van v dist[v] = dist[u] + gewicht heapq.heappush(pq, (dist[v], v)) # Print de kortste afstanden opgeslagen in dist[] for i in range(self.V): print(f'{i} {dist[i]}') # Chauffeurscode if __name__ == '__main__': # maak de grafiek uit bovenstaande afbeelding V = 9 g = Graph(V) # maak de hierboven weergegeven grafiek g.addEdge(0, 1, 4) g.addEdge(0, 7, 8) g.addEdge(1, 2, 8) g.addEdge(1, 7, 11) g.addEdge(2, 3, 7) g.addEdge(2, 8, 2) g.addEdge(2, 5, 4) g.addEdge(3, 4, 9) g.addEdge(3, 5, 14) g.addEdge(4, 5, 10) g.addEdge(5, 6, 2) g.addEdge(6, 7, 1) g.addEdge(6, 8, 6) g.addEdge(7, 8, 7) g.shortestPath(0)> C# using System; using System.Collections.Generic; // This class represents a directed graph using // adjacency list representation public class Graph { private const int INF = 2147483647; private int V; private List [] bijvoeglijk naamwoord; public Graph(int V) {// Aantal hoekpunten this.V = V; // In een gewogen grafiek moeten we hoekpunten // en een gewichtspaar opslaan voor elke rand this.adj = new List [V]; voor (int i = 0; ik< V; i++) { this.adj[i] = new List (); } } public void AddEdge(int u, int v, int w) { this.adj[u].Add(new int[] { v, w }); this.adj[v].Add(nieuwe int[] { u, w }); } // Drukt de kortste paden af van src naar alle andere hoekpunten public void ShortestPath(int src) {// Maak een prioriteitswachtrij om hoekpunten op te slaan die // worden voorbewerkt. GesorteerdeSet pq = nieuwe SortedSet (nieuwe DistanceComparer()); // Maak een array voor afstanden en initialiseer alles // afstanden als oneindig (INF) int[] dist = new int[V]; voor (int i = 0; ik< V; i++) { dist[i] = INF; } // Insert source itself in priority queue and initialize // its distance as 0. pq.Add(new int[] { 0, src }); dist[src] = 0; /* Looping till priority queue becomes empty (or all distances are not finalized) */ while (pq.Count>0) {// Het eerste hoekpunt in paar is de minimale afstand // hoekpunt, haal het uit de prioriteitswachtrij. // hoekpuntlabel wordt opgeslagen als seconde van een paar (het // moet op deze manier worden gedaan om de hoekpunten // gesorteerd op afstand te houden) int[] minDistVertex = pq.Min; pq.Remove(minDistVertex); int u = minDistVertex[1]; // 'i' wordt gebruikt om alle aangrenzende hoekpunten van een // vertex foreach (int[] adjVertex in this.adj[u]) {// Haal het hoekpuntlabel op en het gewicht van de huidige // aangrenzend aan u. int v = adjVertex[0]; int gewicht = adjVertex[1]; // Als er een korter pad is naar v via u. if (dist[v]> dist[u] + gewicht) {// Afstand van v dist[v] = dist[u] + gewicht bijwerken; pq.Add(nieuwe int[] { dist[v], v }); } } } // Druk de kortste afstanden af die zijn opgeslagen in dist[] Console.WriteLine('Vertex Distance from Source'); voor (int i = 0; ik< V; ++i) Console.WriteLine(i + ' ' + dist[i]); } private class DistanceComparer : IComparer { public int Compare(int[] x, int[] y) { if (x[0] == y[0]) { return x[1] - y[1]; } retourneer x[0] - y[0]; } } } public class Programma {// Stuurprogrammacode public static void Main() {// maak de grafiek uit bovenstaande figuur int V = 9; Grafiek g = nieuwe grafiek(V); // maak de hierboven weergegeven grafiek g.AddEdge(0, 1, 4); g.AddEdge(0, 7, 8); g.AddEdge(1, 2, 8); g.AddEdge(1, 7, 11); g.AddEdge(2, 3, 7); g.Edge toevoegen(2, 8, 2); g.Edge toevoegen(2, 5, 4); g.AddEdge(3, 4, 9); g.AddEdge(3, 5, 14); g.Edge toevoegen(4, 5, 10); g.AddEdge(5, 6, 2); g.AddEdge(6, 7, 1); g.AddEdge(6, 8, 6); g.AddEdge(7, 8, 7); g.KortstePad(0); } } // deze code is bijgedragen door bhardwajji> Javascript // javascript Program to find Dijkstra's shortest path using // priority_queue in STL const INF = 2147483647; // This class represents a directed graph using // adjacency list representation class Graph { constructor(V){ // No. of vertices this.V = V; // In a weighted graph, we need to store vertex // and weight pair for every edge this.adj = new Array(V); for(let i = 0; i < V; i++){ this.adj[i] = new Array(); } } addEdge(u, v, w) { this.adj[u].push([v, w]); this.adj[v].push([u, w]); } // Prints shortest paths from src to all other vertices shortestPath(src) { // Create a priority queue to store vertices that // are being preprocessed. This is weird syntax in C++. // Refer below link for details of this syntax // https://www.techcodeview.com let pq = []; // Create a vector for distances and initialize all // distances as infinite (INF) let dist = new Array(V).fill(INF); // Insert source itself in priority queue and initialize // its distance as 0. pq.push([0, src]); dist[src] = 0; /* Looping till priority queue becomes empty (or all distances are not finalized) */ while (pq.length>0) {// Het eerste hoekpunt in paar is de minimale afstand // hoekpunt, haal het uit de prioriteitswachtrij. // hoekpuntlabel wordt opgeslagen als tweede van een paar (het // moet op deze manier worden gedaan om de hoekpunten // gesorteerde afstand te behouden (afstand moet het eerste item zijn // in paar) let u = pq[0][1]; pq.shift(); // 'i' wordt gebruikt om alle aangrenzende hoekpunten van een // hoekpunt te verkrijgen for(laat i = 0; i< this.adj[u].length; i++){ // Get vertex label and weight of current // adjacent of u. let v = this.adj[u][i][0]; let weight = this.adj[u][i][1]; // If there is shorted path to v through u. if (dist[v]>dist[u] + gewicht) {/ // Afstand van v bijwerken dist[v] = dist[u] + gewicht; pq.push([dist[v], v]); pq.sort((a, b) =>{ if(a[0] == b[0]) retourneer a[1] - b[1]; retourneer a[0] - b[0]; }); } } } // Druk de kortste afstanden af die zijn opgeslagen in dist[] console.log('Vertex Distance from Source'); voor (laat i = 0; i< V; ++i) console.log(i, ' ', dist[i]); } } // Driver's code // create the graph given in above figure let V = 9; let g = new Graph(V); // making above shown graph g.addEdge(0, 1, 4); g.addEdge(0, 7, 8); g.addEdge(1, 2, 8); g.addEdge(1, 7, 11); g.addEdge(2, 3, 7); g.addEdge(2, 8, 2); g.addEdge(2, 5, 4); g.addEdge(3, 4, 9); g.addEdge(3, 5, 14); g.addEdge(4, 5, 10); g.addEdge(5, 6, 2); g.addEdge(6, 7, 1); g.addEdge(6, 8, 6); g.addEdge(7, 8, 7); // Function call g.shortestPath(0); // The code is contributed by Nidhi goel.> Uitvoer
Vertex Distance from Source 0 0 1 4 2 12 3 19 4 21 5 11 6 9 7 8 8 14>
Tijdcomplexiteit: O(E * logV), waarbij E het aantal randen is en V het aantal hoekpunten.
Hulpruimte: O(V)
Toepassingen van Dijkstra’s algoritme:
- Google-kaarten gebruikt het Dijkstra-algoritme om de kortste afstand tussen bron en bestemming weer te geven.
- In computer netwerken vormt het algoritme van Dijkstra de basis voor verschillende routeringsprotocollen, zoals OSPF (Open Shortest Path First) en IS-IS (Intermediate System to Intermediate System).
- Transport- en verkeersmanagementsystemen gebruiken het algoritme van Dijkstra om de verkeersstroom te optimaliseren, congestie te minimaliseren en de meest efficiënte routes voor voertuigen te plannen.
- Luchtvaartmaatschappijen gebruiken het algoritme van Dijkstra om vliegroutes te plannen die het brandstofverbruik minimaliseren en de reistijd verkorten.
- Het algoritme van Dijkstra wordt toegepast in elektronische ontwerpautomatisering voor het routeren van verbindingen op geïntegreerde schakelingen en zeer grootschalige integratiechips (VLSI).
Voor een uitgebreidere uitleg verwijzen wij u naar dit artikel Dijkstra's kortste pad-algoritme met behulp van prioriteit_wachtrij van STL .





