在matlab中fowEdges,Solve shortest path problem in graph

Create a directed graph with 6 nodes and 11 edges.

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)

DG =

(4,1) 0.4500

(6,2) 0.4100

(2,3) 0.5100

(5,3) 0.3200

(6,3) 0.2900

(3,4) 0.1500

(5,4) 0.3600

(1,5) 0.2100

(2,5) 0.3200

(1,6) 0.9900

(4,6) 0.3800

Display the graph.

h = view(biograph(DG,[],'ShowWeights','on'))

b50610bf1f269bec4acf5088030496b4.png

Biograph object with 6 nodes and 11 edges.

Find the shortest path from node 1 to node 6.

[dist,path,pred] = graphshortestpath(DG,1,6)

dist = 0.9500

path = 1×4

1 5 4 6

pred = 1×6

0 6 5 5 1 4

Mark the nodes and edges of the shortest path by coloring them red and increasing the line width.

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',1.5)

3a8583c1faa1a0b0971512b197b65a07.png

pred contains predecessor nodes of the shortest paths from node 1, the source node, to all other nodes, not only the specified destination node. You can use pred to query the shortest paths from the source node to any other node in the graph.

For instance, to figure out the shortest path from node 1 to node 4 using the information in pred, query pred with the destination node as the first query. Then use the returned answer to get the next node. Repeat this procedure until you get the query answer as 0, which indicates the source node.

next = pred(4)

next = 5

next = pred(next)

next = 1

next = pred(next)

next = 0

The results indicate that the shortest path from node 1 to node 4 is 1->5->4.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值