Dijkstra算法matlab代码
时间: 2023-11-05 14:00:34 浏览: 187
以下是Dijkstra算法的Matlab代码实现:
```matlab
function [dist, path] = dijkstra(adj, start, dest)
% Dijkstra's shortest path algorithm
% Input: adj - adjacency matrix representing the graph
% start - starting node
% dest - destination node
% Output: dist - shortest distance from start to dest
% path - shortest path from start to dest
% Author: Jianyu Zhao
n = size(adj, 1); % number of nodes in the graph
dist = inf(1, n); % initialize distances to infinity
prev = zeros(1, n); % initialize previous node indices to zero
visited = zeros(1, n); % initialize visited nodes to zero
dist(start) = 0; % distance from start to start is zero
for i = 1:n-1 % loop through all nodes except the destination
% find the node with the shortest distance that has not been visited
[mindist, u] = min(dist .* (1 - visited));
visited(u) = 1; % mark the node as visited
% update the distances of adjacent nodes
for v = 1:n
if adj(u, v) ~= 0 % if there is an edge between u and v
alt = dist(u) + adj(u, v); % calculate the alternate distance
if alt < dist(v) % if the alternate distance is less than the current distance
dist(v) = alt; % update the distance
prev(v) = u; % update the previous node index
end
end
end
end
% construct the shortest path from start to dest
path = dest;
while prev(path(1)) ~= 0 % while there are still previous nodes to add
path = [prev(path(1)), path]; % prepend the previous node to the path
end
end
```
该算法使用了邻接矩阵表示图,并且返回了起点到终点的最短距离和最短路径。
阅读全文