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)