【7.19 graphshortestpath graphallshortestpaths函数】matlab 求最短路径函数总结

graphshortestpath 函数是用来解决最短路径问题的。

语法为:

  [dist, path, pred]=graphshortestpath(G,S)
  [dist, path, pred]=graphshortestpath(G,S,T)

  G是稀疏矩阵,S是起点,T是终点。dist表示最短距离,path表示最短距离经过的路径节点,pred表示从S到每个节点的最短路径中,目标节点的先驱,即目标节点的前面一个节点。比如一共有6个点,S=1,那么运行这个函数后pred存的就是S=1这个节点到其它节点T'最短路径上T'的前一个节点。这个函数也就是求出图G上S到T的[distpathpred],当不写T时表示求S到其它所有点的[distpathpred]。

  G是个稀疏矩阵,我的理解是稀疏矩阵就是含有大量0的矩阵,可能为了便于存储和加快计算,才采用这种矩阵。G并不是图的路径权值矩阵,它由s[]向量和t[]向量和路径权值向量w[]构成:G=spares(s,t,w)。也就是说G应该是个N*3的矩阵,第一行表示节点起点,第二行表示节点终点,第三行是权值。而且同一条无向边不用重复写,因为先这样构造的是个有向图。无向图需要这样操作:UG=tril(G+G');就是把G和自己的转置G'加起来再求下三角矩阵。

  对于无向图、有向图搞明白了其它的就是一些参数、属性的调整了。

  附上文档中的代码,有改动:

clc;
W = [.41 .99 .51 .32 .15 .45 .38 .32 .36 .29 .21];
DG = sparse([6 1 2 2 3 4 4 5 5 6 1],[2 6 3 5 4 1 6 3 4 3 5],W);
h=view(biograph(DG,[],'ShowWeights','on'))
[dist,path,pred]=graphshortestpath(DG,1,6,'Directed','true')
set(h.Nodes(path),'Color',[1 0.4 0.4])
edges=getedgesbynodeid(h,get(h.Nodes(path),'ID'));%我觉得这里就是获得最短路径的边和ID
set(edges,'LineColor',[1 0 0])
set(edges,'LineWidth',1.5)
UG=tril(DG+DG');
bg=biograph(UG,[],'ShowArrows','off','ShowWeights','on');
h=view(bg)
set(bg.nodes,'shape','circle');
[dist,path,pred]=graphshortestpath(UG,1,6,'Directed','false')
set(h.Nodes(path),'Color',[1 0.4 0.4])
fowEdges=getedgesbynodeid(h,get(h.Nodes(path),'ID'));
revEdges=getedgesbynodeid(h,get(h.Nodes(fliplr(path)),'ID'));%这里fliplr是反转操作,比如把[1 2 3]变成[3 2 1]。由于是无向图,所以正反都要求。
edges=[fowEdges;revEdges];
set(edges,'LineColor',[0.6 0.4 0.1])
set(edges,'LineWidth',1.5)

  

  

而对于graphallshortestpaths函数则是求所有点之间的最短距离:[dist] = graphallshortestpaths(G)

道理和上面那个函数很相似,当然内部实现的算法是不一样的。

这还是文档里的例程:

W = [.41 .99 .51 .32 .15 .45 .38 .32 .36 .29 .21];
DG = sparse([6 1 2 2 3 4 4 5 5 6 1],[2 6 3 5 4 1 6 3 4 3 5],W);
view(biograph(DG,[],'ShowWeights','on'))
graphallshortestpaths(DG)
UG = tril(DG + DG')
view(biograph(UG,[],'ShowArrows','off','ShowWeights','on'))

  

原文地址:https://www.cnblogs.com/zxhyxiao/p/9338481.html