Python data structure and algorithm--the shortest path of graphs (Dijkstra algorithm)

Source: Internet
Author: User

1 #Dijkstra algorithm--Relaxation by edges2 #specify a path to a point to each of the other vertices--single source Shortest path3 4 #Initialization diagram Parameters5G = {1:{1:0, 2:1, 3:12},62:{2:0, 3:9, 4:3},73:{3:0, 5:5},84:{3:4, 4:0, 5:13, 6:15},95:{5:0, 6:4},Ten6:{6: 0}} One      A  - #each time a vertex closest to the source point is found, then the center of gravity for the vertex expands - #The shortest path to the source point to all remaining points the #a greedy algorithm -  - defDijkstra (g,v0,inf=999): -     """calculates the distance from a specified point v0 to the shortest path of any point in figure G using the Dijkstra algorithm + INF is a set infinite distance value - This method does not solve the graph of negative weight edges +     """ ABook =set () atMINV =V0 -      -     #The initial distance from the source vertex to the remaining vertices -dis = Dict ((k,inf) forKinchG.keys ()) -Dis[v0] =0 -      in      whileLen (book) <Len (G): -Book.add (MINV)#determine the distance from the current vertex to          forWinchG[MINV]:#spread out at the center of the current point +             ifDIS[MINV] + g[minv][w] < Dis[w]:#if the distance from the current point to a point is small and the shortest distance known -DIS[W] = Dis[minv] + g[minv][w]#update a known distance the          *New = INF#Select the minimum distance point from the remaining indeterminate points as the new diffusion point $          forVinchDis.keys ():Panax Notoginseng             ifVinchBookContinue -             ifDIS[V] <NEW: theNew =Dis[v] +MINV =v A     returnDis the  +  -dis = Dijkstra (g,v0=1) $ PrintDis.values ()

Python data structure and algorithm--the shortest path of graphs (Dijkstra algorithm)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.