#################本文为学习《图论算法及其MATLAB实现》的学习笔记#################
算法用途
图中任意两点间最短路的求法
算法思想
利用求最短路的Floyd算法的思想。
首先,求得最短距离矩阵;
然后,求任意给定两个顶点间的最短路所包含的顶点。
程序参数说明
W: 图的权值矩阵
k1: 始点
k2: 终点
P: k1,k2之间的最短路,顶点以经过次序排列
u: 最短路的距离
算法的matlab程序详解
%求任意两顶点间的最短路
function [ P, u ] = n2shorf( W,k1,k2 )
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%% 输入: W: 图的权值矩阵
%%%%%%%%% k1: 始点
%%%%%%%%% k2: 终点
%%%%%%%%% 输出: P: k1,k2之间的最短路,顶点以经过次序排列
%%%%%%%%% u: 最短路的距离
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%% 初始化 %%%%%%%%%%
n = length(W); % 计算顶点数
U = W; % 保存任意两点之间最短路径的长度
m = 1;
%%%%%%%%%% 利用Floyd算法思想,求最短距离矩阵 %%%%%%%%%%
while m <= n
for i = 1:n
for j = 1:n
if U(i,j) > U(i,m) + U(m,j)
U(i,j) = U(i,m) + U(m,j);
end
end
end
m = m+1;
end
u = U(k1,k2); % 始点到终点的最短距离
%%%%%%%%%% 求任意两顶点间的最短路所包含的顶点 %%%%%%%%%%
P1 = zeros(1,n); % P1 为最短路径的反序
k = 1;
P1(k) = k2;
V = ones(1,n) * inf;
kk = k2;
while kk ~= k1 % 判断此时终点是否为始点,即是否找完所有中转点
for i = 1:n % 寻找所有中转点
V(1,i) = U(k1,kk) - W(i,kk); % 计算始点到终点的最短距离与中转点到终点最短距离的差值
if V(1,i) == U(k1,i);
P1(k+1) = i; % 将此时的中转点增加到最短路径队列
kk = i; % 将此时的中转点设置为新的终点
k = k+1;
end
end
end
%%%%%%%%% 将 P1 的反序路径重新正序排列 %%%%%%%%%
k = 1;
wrow = find(P1 ~= 0); % 找到最短路径中的所有顶点
for j = length(wrow):(-1):1 % 由最短路径的总顶点数以 -1 为步长反向遍历至始点
P(k) = P1(wrow(j)); % 重新排列最短路径队列
k = k+1;
end
P;