迪杰斯特拉最短路径代码
时间: 2023-07-10 19:35:37 浏览: 184
以下是使用 Python 实现的迪杰斯特拉最短路径算法的代码:
```python
import heapq
def dijkstra(graph, src):
dist = {node: float('inf') for node in graph} # 到源节点的距离
dist[src] = 0
pq = [(0, src)] # 优先队列,按距离排序
while pq:
(d, u) = heapq.heappop(pq)
if d > dist[u]:
continue
for v, weight in graph[u].items():
if dist[u] + weight < dist[v]:
dist[v] = dist[u] + weight
heapq.heappush(pq, (dist[v], v))
return dist
```
其中,`graph` 是图的邻接表表示,`src` 是源节点。函数返回一个字典,其中键为节点,值为到源节点的最短距离。
相关问题
迪杰斯特拉最短路径完整代码matlab
以下是迪杰斯特拉算法的完整代码,使用Matlab编写:
```matlab
function [distances, previous] = dijkstra(adjacency_matrix, start_node)
% DIJKSTRA Calculates the shortest path between nodes in a graph using the Dijkstra algorithm
% [distances, previous] = DIJKSTRA(adjacency_matrix, start_node) returns the distances
% from the start_node to each node in the graph and the previous node for each node on the
% shortest path from start_node to that node.
%
% adjacency_matrix is a square matrix representing the weighted edges of the graph
% start_node is the index of the starting node
%
% Example usage:
%
% >> adjacency_matrix = [0 7 Inf 5; 7 0 8 9; Inf 8 0 Inf; 5 9 Inf 0]
% >> [distances, previous] = dijkstra(adjacency_matrix, 1)
% distances =
% 0 7 15 5
% previous =
% 0 1 2 1
% Initialize variables
num_nodes = size(adjacency_matrix, 1);
visited = false(1, num_nodes);
distances = Inf(1, num_nodes);
previous = zeros(1, num_nodes);
% Set the distance to the start node to 0
distances(start_node) = 0;
% Loop through all nodes in the graph
for i = 1:num_nodes
% Find the node with the smallest distance that has not been visited yet
[min_distance, current_node] = min(distances(~visited));
% If all remaining nodes are inaccessible, break out of the loop
if isempty(current_node)
break;
end
% Mark the current node as visited
visited(current_node) = true;
% Loop through all neighbors of the current node
for j = 1:num_nodes
if adjacency_matrix(current_node, j) ~= Inf && ~visited(j)
% Calculate the distance to the neighbor through the current node
distance = min_distance + adjacency_matrix(current_node, j);
% If the distance is shorter than the current shortest distance to the neighbor, update it
if distance < distances(j)
distances(j) = distance;
previous(j) = current_node;
end
end
end
end
end
```
使用方法:
1. 定义一个邻接矩阵,其中 Inf 表示两个节点之间没有边连接
2. 调用 dijkstra 函数,传递邻接矩阵和起始节点的索引作为参数
3. 函数将返回一个距离数组和前驱节点数组,其中距离数组表示从起始节点到每个节点的最短距离,前驱节点数组表示从起始节点到每个节点的最短路径上每个节点的前一个节点的索引,如果不存在前驱节点,则为0
迪杰斯特拉最短路径c语言
以下是使用C语言实现Dijkstra算法求解最短路径的示例代码:
```c
#include <stdio.h>
#include <limits.h>
#define V 6 // 顶点数
#define INF INT_MAX // 定义无穷大
// 找到距离最小的顶点
int minDistance(int dist[], int visited[]) {
int min = INF, min_index;
for (int v = 0; v < V; v++) {
if (!visited[v] && dist[v] <= min) {
min = dist[v];
min_index = v;
}
}
return min_index;
}
// 打印最短路径
void printPath(int parent[], int j) {
if (parent[j] == -1) return;
printPath(parent, parent[j]);
printf("%d ", j);
}
// 打印结果
void printResults(int dist[], int parent[], int src) {
printf("Vertex\t Distance\t Path\n");
for (int i = 0; i < V; i++) {
printf("%d\t %d\t\t%d ", i, dist[i], src);
printPath(parent, i);
printf("\n");
}
}
// Dijkstra算法求最短路径
void dijkstra(int graph[V][V], int src) {
int dist[V]; // 存储从源点到其他顶点的距离
int visited[V]; // 标记顶点是否已经被访问
int parent[V]; // 存储最短路径的父节点
// 初始化
for (int i = 0; i < V; i++) {
dist[i] = INF;
visited[i] = 0;
parent[i] = -1;
}
dist[src] = 0;
// 求解最短路径
for (int count = 0; count < V-1; count++) {
int u = minDistance(dist, visited);
visited[u] = 1;
for (int v = 0; v < V; v++) {
if (!visited[v] && graph[u][v] && dist[u] + graph[u][v] < dist[v]) {
parent[v] = u;
dist[v] = dist[u] + graph[u][v];
}
}
}
// 打印结果
printResults(dist, parent, src);
}
int main() {
int graph[V][V] = {
{ 0, 2, 4, 0, 0, 0 },
{ 2, 0, 1, 4, 2, 0 },
{ 4, 1, 0, 0, 3, 0 },
{ 0, 4, 0, 0, 3, 2 },
{ 0, 2, 3, 3, 0, 2 },
{ 0, 0, 0, 2, 2, 0 }
};
dijkstra(graph, 0);
return 0;
}
```
上述代码实现了一个6个顶点的图的最短路径求解。其中,graph数组表示图的邻接矩阵,dijkstra函数实现Dijkstra算法,minDistance函数用于找到距离最小的顶点,printPath函数和printResults函数用于打印最短路径的结果。
阅读全文