目录
基础部分:
适用范围:
计算最短路径问题
方法分类:
迪杰斯特拉(Dijkstra)算法
贝尔曼-福特(Bellman-Ford)算法
步骤:
1、列出各点之间的权重矩阵
2、将已知矩阵用matlab语言描述并画出权重图
3、利用matlab中的shortestpath计算最短路径
注意事项:
负权回路图(尤其存在负权值的无向图)无法计算最短路径问题
matlab代码部分:
%画无向无权图:
s1 = [1,2,3,4];
t1 = [2,3,1,1];
G1 = graph(s1, t1);
plot(G1)
%画无向有权图:
s = [1,2,3,4];
t = [2,3,1,1];
w = [3,8,9,2];
G = graph(s, t, w);
plot(G, 'EdgeLabel', G.Edges.Weight, 'linewidth', 2)
set( gca, 'XTick', [], 'YTick', [] );
%画有向无权图:
s = [1,2,3,4,1];
t = [2,3,1,1,4];
G = digraph(s, t);
plot(G)
set( gca, 'XTick', [], 'YTick', [] );
%画有向有权图:
s = [1,2,3,4];
t = [2,3,1,1];
w = [3,8,9,2];
G = digraph(s, t, w);
plot(G, 'EdgeLabel', G.Edges.Weight, 'linewidth', 2)
set( gca, 'XTick', [], 'YTick', [] );
%计算最短路径实例:
%%原始的各点的权重矩阵
%[0 50 ∞ 40 25 10;
%50 0 15 20 ∞ 25;
%∞ 15 0 10 20 ∞;
%40 20 10 0 10 25;
%25 ∞ 20 10 0 55;
%10 25 ∞ 25 55 0]
s = [1 1 1 1 2 2 2 3 3 4 4 5];
t = [2 4 5 6 3 4 6 4 5 5 6 6];
w = [50 40 25 10 15 20 25 10 20 10 25 55 ];
G = graph(s,t,w);
plot(G, 'EdgeLabel', G.Edges.Weight, 'linewidth', 1)
[P,d] = shortestpath(G, 1, 2) %计算最短路径d及具体路径描述P
myplot = plot(G, 'EdgeLabel', G.Edges.Weight, 'linewidth', 1);
highlight(myplot, P, 'EdgeColor', 'r')
D = distances(G) %返回任意两点的距离矩阵
[nodeIDs,dist] = nearest(G, 2, 30) %找到距离点2小于30的点的名称nodeIDs和距离dist
matlab的学习部分:
设置图像的坐标无数值:set(gca,'Xtick',[],'YTick',[]);
将权重放入图中:plot(G, 'EdgeLabel', G.Edges.Weight,)
将图中的线段加粗:plot(G,'linewidth',2)
计算最短路径:[P,d] = shortestpath(G, start, end [,'Method', algorithm] )
G:输入图 start:起始的节点 end:目标的节点 [,'Method', algorithm]可选,一般无需手动设置,会自动选择适合的算法
可选的算法:'auto'(默认); ‘unweighted’(计算无权图) 'positive'(迪杰斯特拉算法) ‘mixed' (Bellman-Ford算法)
返回任意两点的距离矩阵:d = distance(G[,'method',algorithm]);
找给定范围内所有的点:[nodeIDs,dist] = nearest(G,s,d [,'Method', algorithm])