我在python中使用递归函数有点困惑.Below是我在python中的代码,它检查给定的一组点是否形成一个acylcic图。输入格式如下:输入中的前两个数字由顶点数和边数组成。下面的剩余数字表示形成边缘的顶点,其方向是从左数到右数。例如,检查下面的图像
以下是解决此问题的代码。输出提供图中的循环次数
#Uses python3
import sys
def acyclic(adj,cc,in_path):
# check if value of ad
global clock
global cycles
clock += 1
for i in adj:
for j in i:
if visited[j] != 1:
num = reach(adj,j,cc,in_path)
if (0 not in visited):
return cc
cc += 1
return cc
def reach(adj,x,cc,in_path):
visited[x] = 1
# preVisit(x)
global cycles
cnum[x] = cc
print(x)
in_path.append(x)
print(in_path)
for i in adj[x]:
print(adj[x])
if visited[i] != 1:
return reach(adj,i,cc,in_path)
elif i in in_path:
# print("in path")
cycles += 1
return (cycles)
break
# postVisit(x)
# return visited[x]
def dfs(adj):
global m
global cycles
# print(m)
for i in range(n):
in_path = []
if visited[i] != 1:
reach(adj,i,0,in_path)
print (cycles)
def preVisit(x):
global clock
clock += 1
prev[x] = clock
# print("prev")
# print(prev)
def postVisit(x):
global clock
clock += 1
postV[x] = clock
# print("post")
# print(postV)
if __name__ == '__main__':
cycles = 0
clock = 0
input = sys.stdin.read()
data = list(map(int, input.split()))
n, m = data[0:2]
data = data[2:]
edges = list(zip(data[0:(2 * m):2], data[1:(2 * m):2]))
prev = [0 for _ in range(n)]
postV = [0 for _ in range(n)]
adj = [[] for _ in range(n)]
cnum = [0 for i in range(n)]
visited = [0 for i in range(n)]
for (a, b) in edges:
adj[a - 1].append(b - 1)
print(adj)
dfs(adj)
每当我在函数return "reach(adj,i,cc,in_path)"
中使用"return(cycles)"
和reach()
时,我都会得到正确答案。但是,取下它们会给我错误的答案。有人可以解释一下为什么会这样吗?
提前致谢
此致
Rishit