迪杰斯特拉算法求最短路径matlab完整代码
时间: 2023-06-22 17:25:04 浏览: 86
以下是迪杰斯特拉算法求最短路径的 Matlab 完整代码:
```matlab
function [dist, path] = dijkstra(graph, startNode, endNode)
% Dijkstra's algorithm to find shortest path
% Inputs:
% graph: adjacency matrix of the graph
% startNode: starting node
% endNode: destination node
% Outputs:
% dist: shortest distance from startNode to endNode
% path: shortest path from startNode to endNode
n = size(graph, 1); % number of nodes
dist = inf(1, n); % initialize distance to all nodes as infinity
visited = zeros(1, n); % mark all nodes as unvisited
prev = zeros(1, n); % array to store previous node in optimal path
dist(startNode) = 0; % distance from start node to itself is zero
for i = 1:n-1
% find the node with the minimum distance
[u, minDist] = minDistance(dist, visited);
visited(u) = 1; % mark the node as visited
% update the distance of the adjacent nodes
for v = 1:n
if graph(u, v) ~= 0 && visited(v) == 0
alt = dist(u) + graph(u, v);
if alt < dist(v)
dist(v) = alt;
prev(v) = u;
end
end
end
end
% compute the shortest path
path = endNode;
while path(1) ~= startNode
path = [prev(path(1)), path];
end
end
function [u, minDist] = minDistance(dist, visited)
% helper function to find the node with the minimum distance
minDist = inf;
for i = 1:length(dist)
if visited(i) == 0 && dist(i) < minDist
u = i;
minDist = dist(i);
end
end
end
```
其中,`graph` 是邻接矩阵,`startNode` 是起点,`endNode` 是终点。函数返回值包括最短距离 `dist` 和最短路径 `path`。
阅读全文