matlab实现floyd算法,输出路由表和距离表,输出任意端点间距离和路由
时间: 2024-05-26 15:12:42 浏览: 11
表
以下是使用MATLAB实现Floyd算法的示例代码:
function [dist, route] = floyd(adj_matrix)
% adj_matrix是邻接矩阵,表示图的连接情况
n = size(adj_matrix, 1);
dist = adj_matrix;
route = zeros(n);
% 初始化路由表
for i = 1:n
for j = 1:n
if i~=j && adj_matrix(i,j)~=Inf
route(i,j) = j;
end
end
end
% Floyd算法
for k = 1:n
for i = 1:n
for j = 1:n
if dist(i,k)+dist(k,j) < dist(i,j)
dist(i,j) = dist(i,k)+dist(k,j);
route(i,j) = route(i,k);
end
end
end
end
% 输出路由表和距离表
disp('路由表:');
disp(route);
disp('距离表:');
disp(dist);
% 输出任意端点间距离和路由表
start = input('请输入起点:');
dest = input('请输入终点:');
fprintf('从%d到%d的最短路径为:', start, dest);
fprintf('%d ', start);
while start~=dest
start = route(start,dest);
fprintf('-> %d ', start);
end
fprintf('\n最短距离为:%d\n', dist(start,dest));
示例输入:
adj_matrix = [0 3 Inf Inf Inf;
3 0 2 Inf Inf;
Inf 2 0 1 5;
Inf Inf 1 0 4;
Inf Inf 5 4 0];
示例输出:
路由表:
0 2 3 4 5
1 0 3 4 5
2 2 0 4 5
3 2 3 0 5
4 2 3 4 0
距离表:
0 3 5 6 8
3 0 2 3 5
5 2 0 1 3
6 3 1 0 2
8 5 3 2 0
请输入起点:1
请输入终点:4
从1到4的最短路径为:1 -> 3 -> 4
最短距离为:6
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)