[Python] Freud (Floyd) algorithm to find the diameter of the graph and record the path

Source: Internet
Author: User
Tags define function

Related concepts

For a figure g= (V, E), figure two points u, V shortest path length, called the Shortest path problem of the graph. The longest in the shortest path is called the diameter of the graph .

In this paper, the shortest path algorithm of two points determined in the figure is called the single source shortest path algorithm. The shortest path algorithm between any two points in the graph is called the multi-source shortest path algorithm.

The common path algorithms are:
    • Dijkstra algorithm
    • SPFA Algorithm \bellman-ford algorithm
    • Floyd algorithm \floyd-warshall algorithm
    • Johnson algorithm

One of the most classic is the Dijkstra algorithm and the Floyd algorithm. The Floyd algorithm is a multi-source shortest path algorithm that can directly find the distance between any two points in the graph, so the diameter of the graph can be obtained by taking the largest of them.

Floyd algorithm algorithm idea

Assuming dis (I,J) is the distance from the shortest path of node u to node V (Shortest path length), for each node k, check whether dis (i,k) + dis (k,j) < dis (I,J) is established, and if so, the path from I to K to J is shorter than I direct to J, It records dis (i,j) = Dis (i,k) + dis (k,j). Therefore, the distance from the shortest path of I to J is recorded when all nodes K,dis (I,J) are traversed.

Algorithm features
    • Using the idea of dynamic programming
    • You can calculate an image without a direction or a graph
    • Short core code (five elements)
    • Can calculate the distance between any two points at once
    • Algorithm complexity O (n^3), is a good algorithm
A key issue

When judging the equation for dis (i,k) + dis (k,j) < dis (i,j), K is chosen if the distance through K is shorter, but can this guarantee that the dis (i,k) and Dis (K,J) have achieved the minimum value at this time?

The answer is yes, you can use the mathematical inductive method to prove that reference to this blog

Example figure g for diameter to be asked

Program input

2 (for the graph without direction)

8 9 (represents 8 vertices, 9 edges)

1 2 5 (indicates the distance weight between vertex 1 and Vertex 2 is 5)

... ...

Program output

(adjacency matrix, matrix element M[i][j] represents the distance between Vertex VI and VJ)

(Shortest path between vertices and path length, for this example, the distance between vertex V4 and V6 or V8 is 10, which is the two vertex pairs farthest away)

(diameter of this figure)

Python Source code
# ----------------------------------------------# project:calculate diameter of graph# Using Floyd algorithm# ----------------------------------------------# define Function:print Shortest PathdefGetPath (i, J):ifI!=J:ifPATH[I][J]== -1:Print('-'J+1, end="')Else: GetPath (i, Path[i][j]) GetPath (Path[i][j], J)defPrintpath (i, J):Print(' Path: ', I+1, end="') GetPath (i, J)Print()Print('----------------program start----------------')# Read DataFlag= input(' Please input type of graph (1:directed '             ' graph; 2:undirected graph]: ') Vertex, Edge= input(' Please input the number of '                     ' Vertex and Edge: '). Strip (). Split ()# initializedFlag= int(flag) Vertex= int(vertex) Edge= int(EDGE) INF= 99999999Dis=[]# matrix of the shortest distancePath=[]# Record the shortest path forIinch Range(vertex): Dis+=[[]] forJinch Range(vertex):ifI==J:dis[i].append (0)Else: Dis[i].append (INF) forIinch Range(vertex): path+=[[]] forJinch Range(vertex): Path[i].append (-1)# Read Weight informationPrint(' Please input weight info (v1 v2 w[v1,v2]): ') forIinch Range(Edge): U, V, W= input(). Strip (). Split () U, V, W= int(u)-1,int(v)-1,int(W)ifFlag== 1: Dis[u][v]=WelifFlag== 2: Dis[u][v]=W Dis[v][u]=WPrint(' The Weight matrix is: ') forIinch Range(vertex): forJinch Range(vertex):ifDIS[I][J]!=Inf:Print('%5d' %DIS[I][J], end="')Else:Print('%5s' % ' ∞ ', end="')Print()# Floyd algorithm forKinch Range(vertex): forIinch Range(vertex): forJinch Range(vertex):ifDIS[I][J]>DIS[I][K]+DIS[K][J]: dis[i][j]=DIS[I][K]+DIS[K][J] Path[i][j]=KPrint(' =========================================== ')# Output The resultPrint(' Output The result: ')ifFlag== 1: forIinch Range(vertex): forJinch Range(vertex):if(I!=J and(Dis[i][j]!=INF):Print(' v%d----> V%dtol_weight: '                      '%3d ' %(I+1J+1, Dis[i][j])) Printpath (i, J)if(I!=J and(Dis[i][j]==INF):Print(' v%d----> V%dtol_weight: '                      ' ∞ ' %(I+1J+1)) Printpath (i, J)ifFlag== 2: forIinch Range(vertex): forJinch Range(I+1, vertex):Print(' v%d<----> v%dtol_weight: '                  '%3d ' %(I+1+ M+1, Dis[i][j]),"', end="') Printpath (i, J)Print() forIinch Range(vertex): forJinch Range(vertex):ifDIS[I][J]==INF:DIS[I][J]= 0# max (dis): The max item of the dimension matrixPrint(' >> the diameter of graph:%d<< ' % Max(Max(DIS)))Print('--------------program end----------------')
Reference

Shortest Path _ Baidu Encyclopedia
Shortest path-dijkstra algorithm and Floyd algorithm
Shortest path problem---Floyd algorithm-CSDN Blog
Floyd algorithm (record Path)-CSDN Blog

[Python] Freud (Floyd) algorithm to find the diameter of the graph and record the path

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.