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

Source: Internet
Author: User

Using the Floyd-warshall algorithm to find the shortest path between two points

Not allowed to have negative edge, high time complexity, simple thinking

1 #City Map (Dictionary of Dictionaries)2 #the 1th key of the dictionary is the starting city, the 2nd key is the target city, its key value is the direct distance between two cities.3 #makes it easy to update the minimum value between two points by setting the non-connected point to INF4INF = 999995G = {1:{1:0, 2:2, 3:6, 4:4},62:{1:inf, 2:0, 3:3, 4: INF},73:{1:7, 2:inf, 3:0, 4:1},84:{1:5, 2:inf, 3:12, 4: 0}9      }Ten  One #algorithm idea: A #each vertex can make the distance between two vertices shorter - #when a third point is not allowed between two points, the shortest path between these cities is the initial path -  the #Floyd-warshall algorithm Core statement - #update the shortest path between points and points, respectively, in cases where only one point K is allowed -  forKinchG.keys ():#constantly trying to add a new point K between two points i,j, update the shortest distance -      forIinchG.keys (): +          forJinchG[i].keys (): -             ifG[I][J] > G[i][k] +G[k][j]: +G[I][J] = G[i][k] +G[k][j] A  at  -  forIinchG.keys (): -     PrintG[i].values ()

Results:

[0, 2, 5, 4] [9, 0, 3,4] [6, 8, 0, 1] [5, 7, 10, 0]

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

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.