ダイクストラ法 Python & C++ (例)

⚡ スマートサマリー

Dijkstra's Algorithm computes the shortest path from a single source vertex to every other vertex in a weighted graph with non-negative edges. This greedy method underpins Google マップルーティング、OSPF IPルーティング、そして無数のネットワーク最短経路のユースケース。

  • 🎯 コアアイデア: 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++ (NAIST) と 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

これら4つのルートのうち、最初のルートのコストは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) 配列またはリストを保持して trac訪問したノードのk個。
ステップ3) ノードのコストを最小コストに更新します。これは、現在のコストとパスのコストを比較することで実行できます(例のセクションで説明しています)。
ステップ4) すべてのノードを訪問するまで、ステップ3を続けます。

これらの手順をすべて完了すると、送信元から宛先までのコストが最小となるパスが見つかります。

ダイクストラとBFS、DFSの違い

ダイクストラ法とBFS-DFSの主な違いは、ダイクストラ法が最短経路探索アルゴリズムであるのに対し、BFSとDFSは一般的な経路探索アルゴリズムであるという点です。一般的に、BFSとDFSは経路探索時に辺のコストを考慮しません。そのため、これらのアルゴリズムは最短経路を保証することはできません。

BFSの動作原理を示す2Dグリッドデモンストレーション

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ルーティングはネットワーク用語です。データパケットがさまざまな経路を経由して受信側に送信される方法を説明します。これらの経路は、ルーター、サーバー、その他の機器で構成されます。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:

  • あるノードから別のノードへは XNUMX つの最短パスが取られます。
  • XNUMX つのノード間の最短パスが選択されると、再度計算されることはありません。

ここで、負のエッジを持つ XNUMX つの例に注目してください。

ダイクストラ法の限界:負のエッジ

左のグラフでは、 頂点は3つあります。ダイクストラ法は、グラフ上で次のように実行されます。

ステップ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におけるAI経路計画エージェントは、重み付きグラフ上で最小コスト経路を見つけるためにダイクストラ法を使用します。強化学習環境も、報酬シェアのための最適な参照経路を計算するためにこのアルゴリズムに依存しています。ping と評価。

はい。GitHub CopilotやGPTのようなAIコーディングアシスタントは、ダイクストラ法を生成できます。 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 Mapsは、A*やConを含む、ダイクストラ法の派生版や後継版を使用しています。trac道路ネットワークと実際の交通状況に合わせて調整された階層構造。累積コストを最小限に抑える貪欲な拡張という基本的な考え方は、依然としてダイクストラの中心的な貢献である。

A*アルゴリズムは、ダイクストラアルゴリズムに目標までの距離に関するヒューリスティックな推定値を追加することで拡張されており、適切なヒューリスティックが利用可能な場合は展開するノードの数を減らします。ダイクストラアルゴリズムはあらゆる方向に探索を行いますが、A*アルゴリズムは目標方向への探索を優先するため、実際にはより高速になります。

地図以外にも、ダイクストラ法はインターネット上のOSPFおよびIS-ISルーティングプロトコル、ネットワークトポロジーの最適化、電話のルーティング、ロボットの動作計画、ソーシャルネットワークにおける最短接続クエリ、航空会社のフライトコスト最小化などに活用されている。