อัลกอริทึมของไดจ์กสตราใน 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 การกำหนดเส้นทางด้วยแผนที่, การกำหนดเส้นทาง IP ด้วย OSPF และกรณีการใช้งานการหาเส้นทางที่สั้นที่สุดในเครือข่ายอีกมากมาย

เส้นทางที่สั้นที่สุด หรือระยะทางที่สั้นที่สุด คืออะไร?
เส้นทางจากจุดเริ่มต้นไปยังจุดปลายทางที่มีค่าใช้จ่ายน้อยที่สุดเรียกว่าเส้นทางที่สั้นที่สุด หรือระยะทางที่สั้นที่สุด ในทฤษฎีกราฟนั้น เป็นไปได้ที่จะมีเส้นทางหลายเส้นทางจากจุดเริ่มต้นไปยังจุดปลายทาง ในบรรดาเส้นทางเหล่านั้น หากมีเส้นทางหนึ่งที่มีค่าใช้จ่ายน้อยที่สุด เราจะเรียกว่าเส้นทางที่สั้นที่สุด
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 เรียกว่า ขอบ (edge)
- "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 |
ในบรรดาเส้นทางทั้งสี่นี้ เราจะเห็นว่าเส้นทางแรกมีค่าใช้จ่าย 7 ดังนั้นจึงเป็นเส้นทางที่สั้นที่สุดในแง่ของค่าใช้จ่าย
เส้นทางที่สั้นที่สุด
อัลกอริทึมของ Dijkstra ทำงานอย่างไร
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) รักษาอาร์เรย์หรือรายการไว้เพื่อเก็บรักษา track ของโหนดที่เยี่ยมชม
ขั้นตอน 3) อัปเดตค่าใช้จ่ายของโหนดด้วยค่าใช้จ่ายต่ำสุด สามารถทำได้โดยการเปรียบเทียบค่าใช้จ่ายปัจจุบันกับค่าใช้จ่ายของเส้นทาง (ดังแสดงในส่วนตัวอย่าง)
ขั้นตอน 4) ดำเนินการขั้นตอนที่ 3 ต่อไปจนกว่าจะเยี่ยมชมโหนดทั้งหมด
หลังจากทำตามขั้นตอนทั้งหมดนี้แล้ว เราจะพบเส้นทางที่มีต้นทุนขั้นต่ำจากต้นทางไปยังปลายทาง
ความแตกต่างระหว่าง Dijkstra และ BFS, DFS
ความแตกต่างหลักระหว่าง Dijkstra และ BFS-DFS คือ Dijkstra เป็นอัลกอริทึมค้นหาเส้นทางที่สั้นที่สุด ในขณะที่ BFS และ DFS เป็นอัลกอริทึมค้นหาเส้นทางทั่วไป ในกรณีทั่วไป BFS และ DFS จะไม่พิจารณาต้นทุนของขอบขณะค้นหาเส้นทาง ดังนั้น อัลกอริทึมเหล่านี้จึงไม่สามารถรับประกันได้ว่าจะเป็นเส้นทางที่สั้นที่สุด
การสาธิตการทำงานของ BFS บนตาราง 2 มิติ
อัลโกสเก็ตช์, แสดงการสาธิต BFS
This demonstration indicates that BFS only finds the path. However, it does not care about the path's weight. BFS (การค้นหาแบบกว้าง - แรก) ถือว่าการเดินทางจากโหนดหนึ่งไปยังอีกโหนดหนึ่งจะมีราคาเพียง 1
เรามาดูตัวอย่างกราฟกัน:
ในที่นี้ 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
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.
โหนด 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:
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 อัลกอริทึมของ Dijkstra
Here is the pseudo-code for Dijkstra's Algorithm:
Dijkstra(G, S): for each vertex V in G distance[V] <- Infinity previous[V] <- NULL if V does not equal S, then, (priority queue) Q.push(V) distance[S] = 0 While Q is not empty U <- Extract the MIN from Q For each unvisited adjacent V of U TotalDistance <- distance[U] + edge_cost(U, V) if TotalDistance is less than distance[V], then distance[V] <- TotalDistance previous[V] <- U return distance, previous
C++ การนำอัลกอริทึมของ Dijkstra ไปใช้
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); }
Output:
Vertex Distance Path 1->2 1 1 2 1->3 7 1 3 1->4 6 1 4 1->5 8 1 4 5 1->6 4 1 2 6 1->7 7 1 2 6 7
Python การนำอัลกอริทึมของ Dijkstra ไปใช้
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)
Output:
Vertex Distance Path 1->1 0 1 1->2 1 1 2 1->3 7 1 3 1->4 6 1 4 1->5 8 1 4 5 1->6 4 1 2 6 1->7 7 1 2 6 7
เราจะเห็นได้ว่าอัลกอริทึมคำนวณระยะทางที่สั้นที่สุดจากโหนดต้นทาง
การประยุกต์ใช้อัลกอริทึม Dijkstra
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 ไม่ได้ใช้อัลกอริทึม Dijkstra แบบธรรมดา แต่ใช้เวอร์ชันที่ดัดแปลงแล้ว เมื่อคุณเลือกปลายทาง มันจะแสดงเส้นทางหลายเส้นทางให้คุณเลือก Google Maps. Among these paths, some are sorted out for the user. These paths are selected based on "time". So, "time" is an edge cost for the shortest path.
Dijkstra ในการกำหนดเส้นทาง IP: การกำหนดเส้นทางไอพี การกำหนดเส้นทาง IP (IP routing) เป็นศัพท์เฉพาะทางด้านเครือข่าย อธิบายถึงวิธีการส่งแพ็กเก็ตข้อมูลของคุณไปยังผู้รับผ่านเส้นทางต่างๆ เส้นทางเหล่านี้ประกอบด้วยเราเตอร์ เซิร์ฟเวอร์ และอุปกรณ์อื่นๆ ในการกำหนดเส้นทาง 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
Dijkstra's algorithm cannot guarantee the shortest path in a graph with negative edges. Dijkstra's algorithm follows these principles:
- เส้นทางที่สั้นที่สุดเส้นหนึ่งจะถูกนำมาจากโหนดหนึ่งไปยังอีกโหนดหนึ่ง
- เมื่อเลือกเส้นทางที่สั้นที่สุดระหว่างสองโหนดแล้ว จะไม่ถูกคำนวณอีก
ต่อไปนี้ ให้สังเกตสองตัวอย่างที่มีขอบเป็นลบ
ในกราฟด้านซ้าย มีจุดยอดสามจุด อัลกอริทึม Dijkstra จะทำงานกับกราฟดังต่อไปนี้:
ขั้นตอน 1) Starting vertex "1" will be initialized to zero. The other nodes will have infinity.
ขั้นตอน 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.
ขั้นตอน 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.
ความซับซ้อนของอัลกอริทึมของ Dijkstra
The implementation above used two "for" loops. These loops run for the number of vertices. So, the time complexity is โอ(วี²). 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 คือจำนวนจุดยอด
ความซับซ้อนของพื้นที่คือ โอ(วี²)เนื่องจากเราใช้เมทริกซ์คำคุณศัพท์ (อาร์เรย์ 2 มิติ) ความซับซ้อนของพื้นที่สามารถปรับให้เหมาะสมได้โดยใช้โครงสร้างข้อมูลแบบรายการที่อยู่ติดกันหรือคิว















