利用graphshortestpath 能夠求最短路徑,具體用法參考MATLAB幫助node
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 =
1 3 4 5 7 9
利用graphallshortestpaths能夠求出全部最短路徑
Dists=graphallshortestpaths(G) %求全部最短路徑spa
Dists =
0 1 2 5 9 6 16 12 19
Inf 0 Inf 6 10 8 17 13 20
Inf Inf 0 3 7 4 14 10 17
Inf Inf Inf 0 4 2 11 7 14
Inf Inf Inf Inf 0 Inf 7 Inf 10
Inf Inf Inf Inf Inf 0 Inf 7 15
Inf Inf Inf Inf Inf Inf 0 Inf 3
Inf Inf Inf Inf Inf Inf Inf 0 10
Inf Inf Inf Inf Inf Inf Inf Inf 0
注意一點的是建立稀疏矩陣的時候,若是原始是m*3的矩陣a,分別表示起點、終點和權值,有n個點,用sparse(a),建立的仍是m*3,這樣根本不對,由於矩陣值是第三列,這樣的話矩陣值包括了下標。應該是sparse(a(:,1),a(:,2),a(:,3)),這樣的話是max(第一列)*max(第二列)的矩陣,而後設置spraseGraph(n,n)=0,這樣的話sparseGraph纔是方陣,採用調用系統的最短路徑函數。對象
clc
clear all
a = [6 1 1
6 4 1
6 5 1
1 2 1
2 3 1
2 4 1
3 5 1
4 5 1];
res = [];
graph = sparse(a(:,1),a(:,2),a(:,3));
graph(6,6) = 0;
P=biograph(graph,[],'ShowWeights','on');%創建有向圖對象P
H=view(P);%顯示各個路徑權值