请给出这段代码的完整修改function [dist,path] = dijkstra(D,s,t) % G:邻接矩阵,s:起点,t:终点 % dist:s到所有点的最短距离,path:s到t的最短路径 n = size(D, 1); dist = inf(1,n); % 到各点的距离 path = zeros(1,n); % 到各点的路径 S = false(1,n); % 是否已经找到最短路径 dist(s) = 0; for i = 1 : n minDist = inf; u = -1; % 找到当前未找到最短路径的点中距离最近的点 for j = 1 : n if ~S(j) && dist(j) < minDist minDist = dist(j); u = j; end end if u == -1 || u == t break; end % 标记已经找到最短路径 S(u) = true; % 更新其它点到起点的距离 for j = 1 : n if ~S(j) && D(u,j)~=0 && dist(j) > dist(u) + D(u,j) dist(j) = dist(u) + D(u,j); path(j) = u; end end end % 构建路径 if path(t) == 0 path = []; else pathNodes = t; while pathNodes ~= s pathNodes = path(pathNodes); path = [pathNodes, path]; end path = [s, path]; end end
时间: 2024-04-29 16:20:08 浏览: 67
floyd_floyd最短路径算法_最短路径矩阵_最短路径_只需要改邻接矩阵_
5星 · 资源好评率100%
function [dist,path] = dijkstra(D,s,t)
% D: 邻接矩阵,s: 起点,t: 终点
% dist: s到所有点的最短距离,path: s到t的最短路径
n = size(D, 1); % 顶点个数
dist = inf(1, n); % 到各点的距离
path = zeros(1, n); % 到各点的路径
S = false(1, n); % 是否已经找到最短路径
dist(s) = 0; % 起点到自己的距离为0
for i = 1 : n
% 找到当前未找到最短路径的点中距离最近的点
minDist = inf;
u = -1;
for j = 1 : n
if ~S(j) && dist(j) < minDist
minDist = dist(j);
u = j;
end
end
% 如果找不到更近的点或者已经找到了终点,则退出循环
if u == -1 || u == t
break;
end
% 标记已经找到最短路径
S(u) = true;
% 更新其他点到起点的距离
for j = 1 : n
if ~S(j) && D(u,j) ~= 0 && dist(j) > dist(u) + D(u,j)
dist(j) = dist(u) + D(u,j);
path(j) = u;
end
end
end
% 构建路径
if path(t) == 0 % 无法到达终点
path = [];
else
pathNodes = t;
while pathNodes ~= s
pathNodes = path(pathNodes);
path = [pathNodes, path];
end
path = [s, path];
end
end
阅读全文