Dijkstra Algoritması Python & C++ (Misal)

⚡ Akıllı Özet

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 Harita tabanlı yönlendirme, OSPF IP yönlendirme ve sayısız ağdaki en kısa yol kullanım senaryosu.

  • 🎯 Ana düşünce: 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 ve DFS'ye kıyasla: BFS ve DFS, kenar ağırlıklarını dikkate almadan herhangi bir yolu bulurken, Dijkstra ağırlıklı kenarlar boyunca toplam maliyeti en aza indirir.
  • 🧭 Adım adım örnek: 7 köşeli ağırlıklı bir grafik, mesafelerin yinelemeli olarak nasıl güncellendiğini ve 1-2-6-7 yolunun 7 maliyetle nasıl kazandığını göstermektedir.
  • ???? Dil Kapsamı: Her ikisi de C++ hem de Python Uygulamalar, minimum mesafe seçim fonksiyonuna sahip komşuluk matrisi sürümünü göstermektedir.
  • ⚠️ Sınırlama: Dijkstra algoritması negatif kenar ağırlıklarında başarısız olur çünkü sonlandırılmış bir düğüm asla yeniden değerlendirilmez; negatif kenarlı grafikler için Bellman-Ford algoritmasını kullanın.
  • 📊 karmaşıklık: Basit dizi sürümü O(V²) zaman ve alan karmaşıklığında çalışır; öncelik kuyruğu seyrek grafikler için süreyi O(E log V)'ye düşürür.

Dijkstra'nın En Kısa Yol Algoritması

En kısa yol veya en kısa mesafe nedir?

Kaynak düğümden hedef düğüme en düşük maliyetli yol, en kısa yol veya en kısa mesafe olarak adlandırılır. Grafik teorisinde, bir kaynaktan bir hedefe birden fazla yol olabilir. Bu yollar arasında, en düşük maliyetli yol varsa, buna en kısa yol denir.

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:

Yönlendirilmemiş Ağırlıklı Grafik

Yönlendirilmemiş Ağırlıklı Grafik

  • 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. düğüm ile 2. düğüm arasındaki yola kenar denir.
  • "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:
Rota veya YolÜcret
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

Bu dört rota arasında, ilk rotanın maliyetinin 7 olduğunu görüyoruz. Dolayısıyla, maliyet açısından en kısa yol budur.

En kısa yol

En kısa yol

Dijkstra Algoritması Nasıl Çalışır?

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 Açgözlü algoritma.

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

) 1 Adım Başlangıç ​​düğümünü 0 maliyetle, diğer düğümleri ise sonsuz maliyetle başlatın.
) 2 Adım Bir dizi veya listeyi muhafaza edin. tracZiyaret edilen düğümlerin k tanesi.
) 3 Adım Düğüm maliyetini minimum maliyetle güncelleyin. Bu işlem, mevcut maliyeti yol maliyetiyle karşılaştırarak yapılabilir (örnek bölümünde gösterilmiştir).
) 4 Adım Tüm düğümler ziyaret edilene kadar 3. adıma devam edin.

Tüm bu adımları tamamladıktan sonra kaynaktan hedefe kadar maliyeti minimum olan yolu bulacağız.

Dijkstra ve BFS, DFS Arasındaki Fark

Dijkstra ve BFS-DFS arasındaki temel fark, Dijkstra'nın en kısa yolu bulma algoritması olması, BFS ve DFS'nin ise genel yol bulma algoritmaları olmasıdır. Genel durumlarda, BFS ve DFS yol bulurken kenar maliyetini dikkate almaz. Bu nedenle, bu algoritmalar en kısa yolu garanti edemez.

BFS'nin Nasıl Çalıştığını Gösteren 2 Boyutlu Izgara Gösterimi

2B Izgara Gösterimi BFS

Algosketch, BFS gösterimini gösteriyor

This demonstration indicates that BFS only finds the path. However, it does not care about the path's weight. BFS (Kapsamlı Arama), bir düğümden diğer düğüme seyahat etmenin yalnızca 1 dolara mal olacağını varsayar.

Şimdi bir örnek grafiğe bakalım:

2B Izgara Gösterim örneği grafiği

Burada, BFS 2. seviyede bir yol buluyor. BFS, grafı seviye sırasına göre tarar. Dolayısıyla, şu şekilde ilerler:

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

) 2 Adım 2, 3 ve 4 numaralı düğümleri 1. seviye olarak işaretleyin ve bitişik düğümleri ziyaret edin. Hedef düğüme ulaşana kadar tüm bitişik düğümleri keşfetmeye devam edecektir.

DFS açısından 1'den 7'ye kadar olan yolu aşağıdaki gibi kat edecektir:

  • 1→2→3→7 (Orijinal Maliyet 10, DFS maliyeti 3)
  • 1→2→6→7 (Orijinal Maliyet 7, DFS maliyeti 3)
  • 1→3→7 (Orijinal Maliyet 8, DFS maliyeti 2)
  • 1→4→5→7 (Orijinal Maliyet 13, DFS maliyeti 3)

Gördüğümüz gibi, DFS yol maliyetini kenar sayısıyla hesaplar. DFS aşağıdaki işlemleri yapar:

  • DFS, kaynaktan (başlangıç ​​tepe noktasından) hedefe kadar bir yol bulabilir.
  • Kaynak düğümden hedefe giden yolun en kısa yol olup olmadığını garanti edemez.

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 Algoritması Örneği

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

Dijkstra algoritmasının bir örneği

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.

Bu işlem için aşağıda adımlar verilmiştir:

) 1 Adım Başlangıç ​​düğüm maliyetini 0 olarak başlatın. Atayın. "Inf" Diğer düğümlere. Bu, kaynak ile düğüm arasında bir yolun bulunmadığı veya yolun henüz ziyaret edilmediği anlamına gelir.

Dijkstra algoritmasının başlatılması

) 2 Adım 1 numaralı düğümü seçtiğinizde, ziyaret edilmiş olarak işaretlenecektir. Ardından, 1 numaralı düğümün tüm komşu düğümlerini güncelleyin. 2, 3, 4, 1 numaralı düğümün komşu düğümleridir.

Bir maliyeti güncellerken aşağıdaki prosedürü izlememiz gerekir:

Dijkstra algoritması güncelleme prosedürü

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 algoritması ilk güncellemeden sonra

) 3 Adım 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 Algoritması güncelleme düğümü 6

Düğüm 3, düğüm 2'nin komşusudur. Ancak önceki adımda maliyetini 7 olarak hesaplamıştık. Şimdi yolumuz 1-2-3 ise düğüm 3'ün maliyeti 10 olacaktır. Yol 1-2- 3'ün fiyatı 10, 1'den 3'e kadar olanların maliyeti ise 7'dir.

) 4 Adım 3 numaralı düğüm için komşu düğüm 7'dir. Dolayısıyla, 7 numaralı düğümün mevcut değerini yol maliyeti (7+1) veya 8 ile karşılaştırarak, 7 numaralı düğümün maliyetini güncelleyeceğiz. Bu da 8'dir. Bu nedenle, 1 numaralı düğümden 7 numaralı düğüme giden bir yol buluyoruz ve bu yol 1→3→7'dir. Maliyet 8'dir.

) 5 Adım 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 algoritması 4. ve 5. adımlardan sonra

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 algoritmasının nihai grafiği

Siyah çizgiyle işaretlenen kenar 1'den 7'ye en kısa yolumuzdur ve bize 7'ye mal olur.

Sözde Code Dijkstra'nın Algoritması

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++ Dijkstra Algoritmasının Uygulanması

To implement Dijkstra's algorithm using C++İşte kod:

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

Çıktı:

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 Dijkstra Algoritmasının Uygulanması

To implement Dijkstra's algorithm using Pythonİşte kod:

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)

Çıktı:

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

Algoritmanın kaynak düğümden en kısa mesafeyi hesapladığını görebiliriz.

Dijkstra Algoritmasının Uygulanması

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'da Google Haritalar: Yukarıdaki kod parçacığı çıktısından da görülebileceği gibi, bu algoritma en kısa yolları bulmanın temelini oluşturmaktadır.

Dijkstra Algoritmasının Uygulanması Google Haritalar

Google Basit Dijkstra algoritmasını kullanmaz. Bunun yerine, değiştirilmiş bir sürümünü kullanır. Bir hedef seçtiğinizde, size birden fazla yol gösterir. 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 Yönlendirmesinde Dijkstra: IP yönlendirme IP yönlendirme, ağ iletişimi terminolojisinde kullanılan bir terimdir. Veri paketinizin farklı yollar üzerinden alıcıya nasıl gönderildiğini açıklar. Bu yollar yönlendiricilerden, sunuculardan ve diğer ekipmanlardan oluşur. IP yönlendirmede farklı protokol türleri vardır.

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 Algoritmasının Sınırlaması

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

  • Bir düğümden diğerine en kısa yol izlenecektir.
  • İki düğüm arasındaki en kısa yol seçildikten sonra tekrar hesaplanmayacaktır.

Burada negatif kenarları olan iki örneğe dikkat edin.

Dijkstra algoritmasının negatif kenarlar konusundaki sınırlaması

Soldaki grafikte, Üç köşe noktası vardır. Dijkstra algoritması grafikte aşağıdaki gibi çalışacaktır:

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

Dijkstra algoritmasının 1. adımının sınırlaması

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

) 3 Adım 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 Adım 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.

Dijkstra algoritmasının 4. adımının sınırlaması

) 5 Adım 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.

Dijkstra Algoritmasının Karmaşıklığı

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). Burada E kenar sayısı, V ise köşe sayısıdır.

Uzay karmaşıklığı O(V²), bir bitişiklik matrisi kullandığımız için (2 boyutlu dizi). Uzay karmaşıklığı, bitişiklik listesi veya kuyruk veri yapısı kullanılarak optimize edilebilir.

SSS

Robotik, otonom araçlar ve oyunlardaki yapay zekâ destekli yol planlama ajanları, ağırlıklı grafiklerde en düşük maliyetli rotaları bulmak için Dijkstra algoritmasını kullanır. Takviyeli öğrenme ortamları da ödül paylaşımı için en uygun referans yollarını hesaplamak için bu algoritmaya güvenir.ping ve değerlendirme.

Evet. GitHub Copilot ve GPT gibi yapay zeka kodlama asistanları, Dijkstra algoritmasını üretebilir. Python, C++ya da JavaBunlara, yığın kullanan öncelik kuyruğu varyantları da dahildir. Ayrıca gerçek en kısa yolu yazdırabilir veya kodu komşuluk listeleri olarak saklanan grafiklere uyarlayabilirler.

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 algoritması, mevcut minimum mesafeyi seçtiği anda bir köşeyi kesinleştirir. Daha sonraki bir negatif kenar, daha uzun bir yolu daha ucuz hale getirebilir, ancak kesinleştirilmiş köşe asla tekrar ziyaret edilmez, bu nedenle algoritma yanlış bir en kısa mesafe bildirir.

Her kenar ağırlığı negatif olmayan değerler olduğunda Dijkstra algoritmasını seçin çünkü O((V+E) log V) çalışma süresiyle daha hızlıdır. Kenarlar negatif olabiliyorsa veya negatif ağırlıklı döngüleri tespit etmeniz gerekiyorsa Bellman-Ford algoritmasını seçin; O(V·E) çalışma süresi bunun dezavantajıdır.

Google Maps, A* ve Con dahil olmak üzere Dijkstra'nın varyantlarını ve ardıllarını kullanır.tracYol ağlarına ve canlı trafiğe göre ayarlanmış hiyerarşik yapılar. Minimum birikmiş maliyetle açgözlü genişleme fikri, hala Dijkstra'nın temel katkısıdır.

A* algoritması, hedefe olan mesafenin sezgisel bir tahminini ekleyerek Dijkstra algoritmasını genişletir ve iyi bir sezgisel yöntem mevcut olduğunda daha az düğüm genişletir. Dijkstra her yöne doğru arama yaparken, A* algoritması aramayı hedefe doğru yönlendirir, bu da onu pratikte daha hızlı hale getirir.

Haritaların ötesinde, Dijkstra internette OSPF ve IS-IS yönlendirme protokollerine, ağ topolojisi optimizasyonuna, telefon görüşmesi yönlendirmesine, robotik hareket planlamasına, sosyal ağlardaki en kısa bağlantı sorgularına ve havayolu uçuş maliyetlerinin en aza indirilmesine güç veriyor.

Bu yazıyı şu şekilde özetleyin: