一、算法步骤
1.给顶点v1标P标号,从出发点v1到终点v1的距离为d(v1)=0,给和被P标号标记的顶点相连的顶点标T标号,d(vi)=L1-j
2.在所有T标号中取最小值,把拥有最小值的T标号标记为P标号,重新生成所有T标记,新生成的T标记重新计算路径d
3.重复以上操作,直到所有顶点达到目标顶点,选取最短路径。
二、算法思想
1.首先假设目标顶点是顶点v,v可以是任意一个顶点
2.其次每一次迭代都可以认为是在寻找到达任意一个顶点的最小值(只要是还没有被标记过的顶点)
3.为什么该算法可以找到两点之间的最短路径,为什么标记过的点不再考虑
(1)首先说明我们遍历了到达各个顶点的所有最短路径(2)我们考虑一般步骤,v5标记为P标记,路径为v1…v5,现在同样有任意一条路径v1…v7路径,这两条路径没有交集,这个时候v1-5<v1-7,继续下一步,假如v7的下一个节点是v5,v1-5<v1-7<v1-7+v7-5。
三、算法程序
程序:tulun1.m weight= [0 2 8 1 Inf Inf Inf Inf Inf Inf Inf; 2 0 6 Inf 1 Inf Inf Inf Inf Inf Inf; 8 6 0 7 5 1 2 Inf Inf Inf Inf; 1 Inf 7 0 Inf Inf 9 Inf Inf Inf Inf; Inf 1 5 Inf 0 3 Inf 2 9 Inf Inf; Inf Inf 1 Inf 3 0 4 Inf 6 Inf Inf; Inf Inf 2 9 Inf 4 0 Inf 3 1 Inf; Inf Inf Inf Inf 2 Inf Inf 0 7 Inf 9; Inf Inf Inf Inf 9 6 3 7 0 1 2; Inf Inf Inf Inf Inf Inf 1 Inf 1 0 4; Inf Inf Inf Inf Inf Inf Inf 9 2 4 0;]; [dis, path]=dijkstra(weight,1, 11)
dijkstra.m
function [min,path]=dijkstra(w,start,terminal)
n=size(w,1); label(start)=0; f(start)=start;
for i=1:n
if i~=start
label(i)=inf;
end, end
s(1)=start; u=start;
while length(s)<n
for i=1:n
ins=0;
for j=1:length(s)
if is(j)
ins=1;
end,
end
if ins0
v=i;
if label(v)>(label(u)+w(u,v))
label(v)=(label(u)+w(u,v));
f(v)=u;
end,
end,
end
v1=0;
k=inf;
for i=1:n
ins=0;
for j=1:length(s)
if is(j)
ins=1;
end,
end
if ins0
v=i;
if k>label(v)
k=label(v); v1=v;
end,
end,
end
s(length(s)+1)=v1;
u=v1;
end
min=label(terminal); path(1)=terminal;
i=1;
while path(i)~=start
path(i+1)=f(path(i));
i=i+1 ;
end
path(i)=start;
L=length(path);
path=path(L?1);
Dijstra算法带权邻接矩阵范例:
[0 2 8 1 Inf Inf Inf Inf Inf Inf Inf; 2 0 6 Inf 1 Inf Inf Inf Inf Inf Inf; 8 6 0 7 5 1 2 Inf Inf Inf Inf; 1 Inf 7 0 Inf Inf 9 Inf Inf Inf Inf; Inf 1 5 Inf 0 3 Inf 2 9 Inf Inf; Inf Inf 1 Inf 3 0 4 Inf 6 Inf Inf; Inf Inf 2 9 Inf 4 0 Inf 3 1 Inf; Inf Inf Inf Inf 2 Inf Inf 0 7 Inf 9; Inf Inf Inf Inf 9 6 3 7 0 1 2; Inf Inf Inf Inf Inf Inf 1 Inf 1 0 4; Inf Inf Inf Inf Inf Inf Inf 9 2 4 0;]
[0 8 Inf Inf Inf Inf 7 8 Inf Inf Inf;
Inf 0 3 Inf Inf Inf Inf Inf Inf Inf Inf;
Inf Inf 0 5 6 Inf 5 Inf Inf Inf Inf;
Inf Inf Inf 0 1 Inf Inf Inf Inf Inf 12;
Inf Inf 6 Inf 0 2 Inf Inf Inf Inf 10;
Inf Inf Inf Inf 2 0 9 Inf 3 Inf Inf;
Inf Inf Inf Inf Inf 9 0 Inf Inf Inf Inf;
8 Inf Inf Inf Inf Inf Inf 0 9 Inf Inf;
Inf Inf Inf Inf 7 Inf Inf 9 0 2 Inf;
Inf Inf Inf Inf Inf Inf Inf Inf 2 0 2;
Inf Inf Inf Inf 10 Inf Inf Inf Inf Inf 0;];
四、算法案例
![](http://qsh.zzeightone.top:81/wp-content/uploads/2019/08/476NW4BCSXD69FN8PRPUL-300x183.png)