How to Use Python to determine whether a directed graph has a ring?

Source: Internet
Author: User

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.

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.