以下是我在网上下的关于用Dijkstra算法算最短路的Matlab程序,望各位大神解释解释里面循环的含义

2024-11-02 14:33:02
推荐回答(1个)
回答1:

lz给个邮箱,我发给你些资料,首先你先得弄明白D算法是什么样的否则怎么看也看不懂的。我有一段代码,可以解释给你听。

function [leng,path] = dijkstra(adj_mat , sta , dst)
m = length(adj_mat);
lengs = linspace(0,0,m);
paths = linspace(0,0,m);
know = linspace(0,0,m);
know(1) = sta;
k=1;
for i = 1:1:m
if i ~= sta
lengs(i) = adj_mat(sta,i);
if lengs(i) ~= inf
paths(i) = sta;
end
end
end
index = 1;
for i = 1:1:m
if i ~= sta
min = inf;
for j = 1:1:m
count = isIn(know,j);
if count == 0 && lengs(j) <= min
k = j;
min = lengs(j);
end
end
know(index) = k;
index = index+1;
for j = 1:1:m
count = isIn(know,j);
if count == 0 && (lengs(i) + adj_mat(i,j)) < lengs(j)
lengs(j) = lengs(i) + adj_mat(i,j);
paths(j) = i;
end
end
end
end
leng = lengs(dst);
k = dst;
j = 1;
path = dst;
while paths(k)~= sta
k = paths(k);
path = [k path];
end
path = [sta path];

其实最关键的步骤就是if count == 0 && (lengs(i) + adj_mat(i,j)) < lengs(j)。判断两点距离与两点中间经过一点距离的大小,而过经过其他一点距离更小则替代原来的值!

至于c,matlab可以直接生成也可以上网找一个,很多的!