#################本文为学习《图论算法及其MATLAB实现》的学习笔记#################
Floyd算法利用动态规划算法的基本思想,核心思想是在找到最短路径矩阵后,将所有顶点设置为中转点重新遍历更新最短路径矩阵。
Floyd算法的基本思想
Floyd算法的基本步骤
程序参数说明
W: 图的权值矩阵
P: 最短路
u: 最短路的权和
算法的matlab程序详解
%Floyd算法
function [ P, u ] = f_path(W)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%% 输入: W: 图的权值矩阵
%%%%%%%%% 输出: P: 最短路
%%%%%%%%% u: 最短路的权和
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%% 初始化 %%%%%%%%%%
n = length(W); % 计算顶点数
U = W; % 保存任意两点之间最短路径的长度
m = 1;
%%%%%%%%%%%%%%% 步骤2 %%%%%%%%%%%%%%%
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); %更新dij
end
end
end
m = m+1;
end
u = U(1,n); % 始点到终点的最短距离
%%%%%%%%%%%%% 输出最短路的顶点 %%%%%%%%%%%%%
P1 = zeros(1,n); % P1 为最短路径的反序
k = 1;
P1(k) = n;
V = ones(1,n) * inf;
kk = n;
while kk ~= 1 % 判断此时终点是否为始点,即是否找完所有中转点
for i = 1:n % 寻找所有中转点
V(1,i) = U(1,kk) - W(i,kk); % 计算始点到终点的最短距离与中转点到终点最短距离的差值
if V(1,i) == U(1,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;