重み付けされたグラフとグラフ内のソース頂点が与えられた場合、 最短経路 ソースから、指定されたグラフ内の他のすべての頂点まで。
注記: 指定されたグラフには負のエッジが含まれていません。
例:
ダイクストラアルゴリズムの実装に関する推奨される実践方法 試してみましょう!入力: src = 0 の場合、グラフは次のようになります。
出力: 0 4 12 19 21 11 9 8 14
説明: 0 から 1 までの距離 = 4。
0 から 2 までの最小距離 = 12。0->1->2
0 から 3 までの最小距離 = 19。0->1->2->3
0 から 4 までの最小距離 = 21。0->7->6->5->4
0 から 5 までの最小距離 = 11。0->7->6->5
0 から 6 までの最小距離 = 9。0->7->6
0 から 7 までの最小距離 = 8。0->7
0 から 8 までの最小距離 = 14。0->1->2->8
アップキャスト
ダイクストラのアルゴリズムを使用 隣接行列 :
アイデアは、 SPT(最短パスツリー) 指定されたソースをルートとして使用します。 2 つのセットで隣接行列を維持します。
- 1 つのセットには最短パス ツリーに含まれる頂点が含まれており、
- 他のセットには、最短パス ツリーにまだ含まれていない頂点が含まれています。
アルゴリズムの各ステップで、他のセット (まだ含まれていないセット) 内にあり、ソースからの距離が最小の頂点を見つけます。
アルゴリズム :
Java乱数ジェネレーター
- セットを作成する sptSet (最短パス ツリー セット)は、最短パス ツリーに含まれる頂点を追跡します。つまり、ソースからの最小距離が計算され、最終的に決定されます。最初、このセットは空です。
- 入力グラフ内のすべての頂点に距離値を割り当てます。すべての距離値を次のように初期化します。 無限 。ソース頂点が最初に選択されるように、ソース頂点の距離値を 0 として割り当てます。
- その間 sptSet すべての頂点が含まれていない
- 頂点を選択してください で それはそこにはありません sptSet 最小距離値を持ちます。
- あなたを含めてください sptSet 。
- 次に、すべての隣接する頂点の距離値を更新します。 で 。
- 距離値を更新するには、隣接するすべての頂点を反復処理します。
- 隣接する頂点ごとに で、 の距離値の合計が で (ソースより) とエッジの重み う~ん 、距離値より小さい で 、次に、の距離値を更新します。 で 。
注記: ブール配列を使用します sptSet[] に含まれる頂点のセットを表す SPT 。値の場合 sptSet[v] が true の場合、頂点 v は SPT 、そうでない場合はそうではありません。配列 距離[] すべての頂点の最短距離の値を保存するために使用されます。
ダイクストラアルゴリズムの図解 :
ダイクストラのアルゴリズムを理解するために、グラフを取得して、ソースからすべてのノードまでの最短パスを見つけてみましょう。
以下のグラフを考慮してください。 ソース = 0
ステップ1:
- セット sptSet 最初は空で、頂点に割り当てられる距離は {0, INF, INF, INF, INF, INF, INF, INF} です。 INF は無限を示します。
- 次に、最小距離値を持つ頂点を選択します。頂点 0 が選択され、それを含めます sptSet 。それで sptSet {0}になります。 0~を含めた後 sptSet 、隣接する頂点の距離値を更新します。
- 0 の隣接する頂点は 1 と 7 です。1 と 7 の距離値は 4 と 8 として更新されます。
次のサブグラフは頂点とその距離値を示しています。有限の距離値を持つ頂点のみが示されています。に含まれる頂点 SPT に示されています 緑 色。
ステップ2:整数を文字列に変換する
- 最小距離値を持ち、まだ含まれていない頂点を選択します。 SPT (ありませんで sptSET )。頂点 1 が選択され、追加されます。 sptSet 。
- それで sptSet は {0, 1} になります。隣接する頂点の距離値を 1 に更新します。
- 頂点 2 の距離値は次のようになります。 12 。
ステップ 3:
- 最小距離値を持ち、まだ含まれていない頂点を選択します。 SPT (ありませんで sptSET )。頂点 7 が選択されます。それで sptSet 今はなる {0、1、7}。
- 7 の隣接する頂点の距離値を更新します。頂点 6 と 8 の距離値は有限になります ( 15と9 それぞれ)。
ステップ 4:
- 最小距離値を持ち、まだ含まれていない頂点を選択します。 SPT (ありませんで sptSET )。頂点 6 が選択されます。それで sptSet 今はなる {0、1、7、6} 。
- 6 の隣接する頂点の距離値を更新します。頂点 5 と 8 の距離値が更新されます。
まで上記の手順を繰り返します。 sptSet 含まれています 指定されたグラフのすべての頂点。最終的に、次の S が得られます。 最も厳しいパス ツリー (SPT)。
上記のアプローチの実装を以下に示します。
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; }>
ジャワ // 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 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 および sptSet[y] == False および dist[y]> dist[x] + self.graph[x][y]: dist[y] = dist[x] + self.graph[x][y] self.printSolution(dist) # ドライバーのコード 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) # このコードは Divyanshu Mehta によって提供され、Pranav Singh Sambyal によって更新されました>>'C#
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>
出力
Vertex Distance from Source 0 0 1 4 2 12 3 19 4 21 5 11 6 9 7 8 8 14>
時間計算量: O(V2)
補助スペース: O(V)
b+ 木
ノート:
- コードは最短距離を計算しますが、パス情報は計算しません。親配列を作成し、距離が更新されたときに親配列を更新し、それを使用してソースから別の頂点までの最短パスを表示します。
- 実装の時間の複雑さは、 O(V 2 ) 。入力の場合 グラフは隣接リストを使用して表現されます 、バイナリ ヒープを使用すると、O(E * log V) に減らすことができます。参照してください 隣接リスト表現のためのダイクストラのアルゴリズム 詳細については。
- ダイクストラのアルゴリズムは、負の重みサイクルを持つグラフでは機能しません。
ダイクストラのアルゴリズムが負のエッジを持つグラフで失敗するのはなぜですか?
負の重みに関する問題は、ダイクストラのアルゴリズムが、ノードが訪問ノードのセットに追加されると、その距離が確定し、変更されないと仮定しているという事実から発生します。ただし、負の重みが存在する場合、この仮定は不正確な結果につながる可能性があります。
例として次のグラフを考えてみましょう。
のインスタンス

上のグラフでは、A はエッジのうちのソース ノードです。 あ に B そして あ に C 、 あ に B はより小さい重みであり、ダイクストラは の最短距離を割り当てます。 B 2 と同様ですが、負のエッジが存在するため、 C に B 、実際の最短距離は 1 に減少しますが、ダイクストラは検出できません。
注記: を使用しております Bellman Ford の最短パス アルゴリズム グラフに負のエッジがある場合に備えて。
ダイクストラのアルゴリズムを使用 隣接リスト O(E logV):
ダイクストラのアルゴリズムでは、常に次の使用をお勧めします。 頂点の距離が減少するたびに、priority_queue に頂点のインスタンスを 1 つ追加します。複数のインスタンスがある場合でも、距離が最小のインスタンスのみが考慮され、他のインスタンスは無視されます。
時間の複雑さは残る O(E * LogV) 優先キューには最大でも O(E) 個の頂点があり、O(logE) は O(logV) と同じです。
上記のアプローチの実装を以下に示します。
C++ // C++ Program to find Dijkstra's shortest path using // priority_queue in STL #include using namespace std; #define INF 0x3f3f3f3f // iPair ==>整数ペア typedef ペア iペア; // このクラスは、 // 隣接リスト表現を使用して有向グラフを表します。 class Graph { int V; // 頂点の数 // 重み付きグラフでは、すべてのエッジ リストの頂点と // 重みのペアを保存する必要があります>* 形容詞;パブリック: グラフ(int V); // コンストラクター // グラフにエッジを追加する関数 void addEdge(int u, int v, int w); // s からの最短パスを出力します voidshortPath(int s); }; // 隣接リストにメモリを割り当てます Graph::Graph(int V) { this->V = V; adj = 新しいリスト [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)); } // src から他のすべての頂点までの最短パスを出力します void Graph::shortestPath(int src) { // 前処理中の頂点を格納する優先キューを作成します。これは C++ の奇妙な構文です。 // この構文の詳細については、以下のリンクを参照してください // https://www.techcodeview.com priority_queue 、より大きい > pq; // 距離のベクトルを作成し、 // すべての距離を無限 (INF) ベクトルとして初期化します。 dist(V, INF); // ソース自体を優先キューに挿入し、 // その距離を 0 として初期化します。 pq.push(make_pair(0, src)); 距離[ソース] = 0; /* 優先キューが空になる (またはすべての距離が確定しない) までループします */ while (!pq.empty()) { // ペアの最初の頂点が最小距離です // 頂点を優先キューから抽出します。 // 頂点ラベルはペアの 2 番目に格納されます ( // 頂点を維持するには、この方法で行う必要があります // ソートされた距離 (距離はペアの // 最初の項目である必要があります) int u = pq.top().second; pq.pop(); // 'i' は頂点リストのすべての隣接する頂点を取得するために使用されます。>::反復子 i; for (i = adj[u].begin(); i != adj[u].end(); ++i) { // u に隣接する現在の // 頂点ラベルと重みを取得します。 int v = (*i).first; int 重み = (*i).秒; // u を介して v へのショートパスがある場合。 if (dist[v]> dist[u] + Weight) { // v の距離を更新 dist[v] = dist[u] + Weight; pq.push(make_pair(dist[v], v)); } } } // dist[] に格納されている最短距離を出力します printf('ソースからの頂点距離
'); for (int i = 0; i< 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; }>
ジャワ import java.util.*; class Graph { private int V; private List> 形容詞; Graph(int V) { this.V = V; adj = 新しい ArrayList(); for (int i = 0; i< 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 = new PriorityQueue(V, Comparator.comparingInt(o -> o.second)); int[] dist = 新しい int[V]; Arrays.fill(dist, Integer.MAX_VALUE); pq.add(new iPair(0, src)); 距離[ソース] = 0; while (!pq.isEmpty()) { int u = pq.poll().second; for (iPair v : adj.get(u)) { if (dist[v.first]> dist[u] + v.sec) { dist[v.first] = dist[u] + v.sec; pq.add(new iPair(dist[v.first], v.first)); System.out.println('ソースからの頂点の距離'); for (int i = 0; i< 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); } }>
パイソン import heapq # iPair ==>整数ペア iPair = tuple # このクラスは # 隣接リスト表現クラスを使用して有向グラフを表します Graph: def __init__(self, V: int): # コンストラクター self.V = V self.adj = [[] for _ in range(V )] def addEdge(self, u: int, v: int, w: int): self.adj[u].append((v, w)) self.adj[v].append((u, w)) # src から他のすべての頂点への最短パスを出力します def ShortestPath(self, src: int): # 前処理中の頂点を格納する優先キューを作成します # pq = [] heapq.heappush(pq, (0, src)) #距離のベクトルを作成し、 # すべての距離を無限 (INF) として初期化します dist = [float('inf')] * self.V dist[src] = 0 while pq: # ペアの最初の頂点が最小距離です# 頂点、優先キューから抽出します。 # 頂点ラベルはペア d の 2 番目に格納されます。u = heapq.heappop(pq) # 'i' は、v の頂点の隣接するすべての頂点を取得するために使用されます。# 重みは self.adj[u]: # If u を経由して v へのパスが短縮されています。 if dist[v]> dist[u] + Weight: # v の距離を更新 dist[v] = dist[u] + Weight heapq.heappush(pq, (dist[v], v)) # に格納されている最短距離を出力dist[] for i in range(self.V): print(f'{i} {dist[i]}') # ドライバーのコード if __name__ == '__main__': # 上図のグラフを作成します V = 9 g = 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)>>C# dist[u] + Weight) { // v の距離を更新 dist[v] = dist[u] + Weight; pq.Add(new int[] { dist[v], v }); } } } // dist[] に保存されている最短距離を出力します Console.WriteLine('ソースからの頂点距離'); for (int i = 0; i< 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]; x[0] - y[0] を返します。 } } } public class Program { // ドライバーコード public static void Main() { // 上図のグラフを作成 int V = 9; グラフ g = 新しいグラフ(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); } } // このコードは 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) { // ペアの最初の頂点は最小距離です。 // 頂点を優先キューから抽出します。 // 頂点ラベルはペアの 2 番目に格納されます ( // 頂点を維持するにはこの方法で行う必要があります // ソートされた距離 (距離はペアの最初の項目である必要があります // ) let u = pq[0][1]; pq.shift(); // 'i' は、頂点のすべての隣接する頂点を取得するために使用されます。 // for(let 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] + Weight) { // v の距離を更新 dist[v] = dist[u] + Weight; pq.push([dist[v], v]); pq.sort((a, b) =>{ if(a[0] == b[0]) return a[1] - b[1]; return a[0] - b[0]; }); } } } // dist[] に保存されている最短距離を出力します console.log('ソースからの頂点距離'); for (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.>
出力
Vertex Distance from Source 0 0 1 4 2 12 3 19 4 21 5 11 6 9 7 8 8 14>
時間計算量: O(E * logV)、E はエッジの数、V は頂点の数です。
補助スペース: O(V)
ダイクストラアルゴリズムの応用:
- グーグルマップ ダイクストラ アルゴリズムを使用して、送信元と宛先の間の最短距離を表示します。
- で コンピューターネットワーキング , ダイクストラのアルゴリズムは、OSPF (Open Shortest Path First) や IS-IS (Intermediate System to Intermediate System) などのさまざまなルーティング プロトコルの基礎を形成します。
- 交通および交通管理システムは、ダイクストラのアルゴリズムを使用して、交通の流れを最適化し、渋滞を最小限に抑え、車両の最も効率的なルートを計画します。
- 航空会社はダイクストラのアルゴリズムを使用して、燃料消費を最小限に抑え、移動時間を短縮する飛行経路を計画します。
- ダイクストラのアルゴリズムは、集積回路および超大規模集積回路 (VLSI) チップ上の配線接続のための電子設計自動化に適用されます。
より詳しい説明については、この記事を参照してください STLのpriority_queueを利用したダイクストラの最短パスアルゴリズム 。