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的[dist, path, pred],當不寫T時表示求S到其它所有點的[dist, path, pred]。
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'))