Python 判断 有向图 是否有环的实例讲解
实例如下:
import numpy from 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 swi = True exit() return # break else: pass print ('s = 0') return False global swi swi = False '''===装载数据''' 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] * c for i in range(1, c+1): s, t = edges[i][0:2] # print (s,' - ', t ) '''GO_OBO文件则 s, t 不需要 -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 - DAG')
用到 numpy 模块,读取的 txt 文件为 有向图的连边,其中第一行 第一个数字 为 边的数量,第二个数字为 节点数 第二行及以后 前两个数字,第一个为 起点, 第二个为 落点。
以上这篇Python 判断 有向图 是否有环的实例讲解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。