https://www.jb51.cc/csharp/1193261.html

编程之家收集整理的这篇文章主要介绍了用C++实现最短路径之Dijkstra算法编程之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

网络层的链路状态路由选择算法(LS算法),其中一种就是用Dijkstra算法写的。《算法导论》的介绍:Dijkstra算法解决的是带权重的有向图上单源最短路径问题,该算法要求所有边的权重都为非负值。

算法思路

  1. G集表示所有点集,S集表示已经求解出源到某点的最短路径的点集,V集表示为求出最短路径的点集
  2. 首先令S=Ø,V=G

如图所示6个点8条边 V={1,2,3,4,5,6}

https://s3-us-west-2.amazonaws.com/secure.notion-static.com/9cf1e0a5-4ec9-4d53-a390-66e81729c45a/162241d3fb5e1ab62b01c2a97a87d4db.png

https://s3-us-west-2.amazonaws.com/secure.notion-static.com/f682a992-c00c-4771-8d0e-afd53cbb977f/68c82e99d7fad04f7f9dff9ea0e3c998.png

  1. 取u=1,把点1放入S中,S={1} ,V={2,3,4,5,6},遍历与点1相连的点,并把权值放入数组

    https://s3-us-west-2.amazonaws.com/secure.notion-static.com/de684205-c2d2-4253-a3c4-659794ee4054/7de8ad84919463a473cdb50c147cbe51.png

    https://s3-us-west-2.amazonaws.com/secure.notion-static.com/1dd3007d-f0a9-43da-8e1e-0064aa5166c3/d2538fd67cfe21edc8b7b3407d471344.png

4.由路径数组可得知此时V集中 点2有最短路径(值为3)所以令u=2,则S={1,2} ,V={3,4,5,6}

因为dis[3]=dis[2]+4 ⇒ 7=3+4 … . dis[5]=dis[2]+9 ⇒ 12=3+9

https://s3-us-west-2.amazonaws.com/secure.notion-static.com/fda94322-e553-4f5e-a1ba-9b8e5c01bbc9/39f858b53b3ce201df6899911d5047d9.png

https://s3-us-west-2.amazonaws.com/secure.notion-static.com/00a745dc-6c52-4e39-90ca-a8d3c0c44b55/3729cb553eb3dc8c0ded152859c58f05.png

  1. 同理如今S={1,2},V={3,4,5,6},在V中发现dis[3]为除dis[1],dis[2]外的最小值,所以令S=S∪{3}此时S={1,2,3},V={4,5,6}

因为dis[5]=12>dis[3]+1=7+1 ⇒ 令 dis[5]=dis[3]+1=7+1=8 因为dis[6]=∞ >dis[3]+6=7+6 ⇒ 令 dis[6]=dis[6]+6=7+6=13

https://s3-us-west-2.amazonaws.com/secure.notion-static.com/c22d3a35-038a-4860-885d-132582961cf6/65b3999bd5475de85b415dd18a2ac933.png

https://s3-us-west-2.amazonaws.com/secure.notion-static.com/badc56d7-5917-4fbb-866d-a4705e9efe2c/8ed297e9c1a0e50d4cff214a4f69bab9.png

  1. 同理如今S={1,2,3},V={4,5,6},在V中发现dis[4]为除dis[1],dis[2],dis[3]外的最小值,所以令S=S∪{4}此时S={1,2,3,4},V={5,6}