How to Use Python to determine whether a directed graph has a ring?
Example:
Import numpyfrom numpy import * def dfs (v): vis [v] =-1 flag = 0 for I in range (n): # print (a [v] [I], '---', vis [I]) if a [v] [I]! = 0 and vis [I]! =-1: dfs (I) vis [I] = 1 else: pass if a [v] [I]! = 0 and vis [I] =-1: print ('yes, there is A loop in this network \ n') global swi = True exit () return # break else: pass print ('s = 0 ') return Falseglobal swiswi = False ''' = loading data ''' edges = numpy.loadtxt('9_nodes_with_r_edge_8_to_3.txt ') # edges = [int (I) for I in edges] bian = int (shape (edges) [0])-1 print (bian, 'edges in the network \ n ') print (shape (edges), '\ n') n = int (edges [0] [1]) c = int (edges [0] [0]) # n, c = input (). split () # n = int (n) # c = int (c) a = [([0] * n) for I in range (n)] vis = [0] * cfor I in range (1, c + 1): s, t = edges [I] [0: 2] # print (s, '-', t) '''go _ OBO file is s, t does not need-1 ''' s = int (s)-1 t = int (t) -1 # s = int (s) # t = int (t) a [s] [t] = 1 # print (a) # print (vis) dfs (0) # print (swi) if not swi: print ('no loop, DAG-DAG ')
When the numpy module is used, the txt file read is the connected edge of the directed graph. The first number in the first row is the number of edges, and the second number is the number of nodes in the second row and the last two digits, the first is the starting point, and the second is the point.
The example of judging whether a directed graph has a ring in Python above is all the content shared by the editor. I hope to give you a reference and support for the help house.