加载中…
个人资料
  • 博客等级:
  • 博客积分:
  • 博客访问:
  • 关注人气:
  • 获赠金笔:0支
  • 赠出金笔:0支
  • 荣誉徽章:
正文 字体大小:

[转载]【转】MATLAB:求最短路径

(2014-01-07 16:48:54)
标签:

转载

分类: 资源链接

利用graphshortestpath 可以求最短路径,具体用法参考MATLAB帮助

Examples:

S=[1 1 2 2 3 3 4 4 4 4 5 6 6 7 8]; %起始节点向量    
E=[2 3 5 4 4 6 5 7 8 6 7 8 9 9 9]; %终止节点向量
W=[1 2 12 6 3 4 4 15 7 2 7 7 15 3 10]; %边权值向量,有向图,G(9,9)=0; 9个节点
G=sparse(S,E,W); %关联矩阵的稀疏矩阵表示
G(9,9)=0;
P=biograph(G,[],'ShowWeights','on');%建立有向图对象P
H=view(P);%显示各个路径权值
[Dist,Path]=graphshortestpath(G,1,9,'Method','Dijkstra') %求节点1到节点9的最短路径
set(H.Nodes(Path),'Color',[1 0.4 0.4]);%以下三条语句用红色修饰最短路径
edges=getedgesbynodeid(H,get(H.Nodes(Path),'ID'));
set(edges,'LineColor',[1 0 0]);
set(edges,'LineWidth',2.0);

%以下是运行结果,节点1到节点9的最短路径为19
Dist =

    19

Path =

                    9

http://hiphotos.baidu.com/lb%CD%BC%EF%BF%BD%EF%BF%BD%EF%BF%BD%EF%BF%BD/pic/item/b0f1dcc66d4e9f7ce4dd3b7f.jpg

利用graphallshortestpaths可以求出所有最短路径
Dists=graphallshortestpaths(G) %求所有最短路径

Dists =

                      16    12    19
   Inf      Inf       10       17    13    20
   Inf   Inf                14    10    17
   Inf   Inf   Inf             11       14
   Inf   Inf   Inf   Inf      Inf      Inf    10
   Inf   Inf   Inf   Inf   Inf      Inf       15
   Inf   Inf   Inf   Inf   Inf   Inf      Inf     3
   Inf   Inf   Inf   Inf   Inf   Inf   Inf       10
   Inf   Inf   Inf   Inf   Inf   Inf   Inf   Inf     0

0

  

新浪BLOG意见反馈留言板 欢迎批评指正

新浪简介 | About Sina | 广告服务 | 联系我们 | 招聘信息 | 网站律师 | SINA English | 产品答疑

新浪公司 版权所有