简单地说,虽然其他一切都很好,但递归中途停止了。
递归函数如下所示(完整代码见here):
def DFS(graph, startNode = 0):
global nodesProcessed; global explored; global finishingTime
explored[startNode] = True
currentLeader = startNode
if startNode in graph:
for neighbor in graph[startNode]:
if not explored[neighbor]:
#checkpoint 1
DFS(graph, neighbor)
#checkpoint 2
else: return currentLeader
nodesProcessed += 1
finishingTime[startNode] = nodesProcessed
return currentLeader
问题是递归了一段时间后就停止了。让我困惑的是:
- 输入是固定的,但是停止的地方不固定。但是总是在调用7000次左右就停止了;
- 所有失败的递归都到达
检查点1
但未能到达检查点2
,并且递归根本不执行; - 它根本没有达到最大递归时间,我已将最大递归时间设置为
sys.setrecursionlimit(10**6)
- 它在相对较小的输入(数百或数千个节点)上运行得很好,但在拥有超过 800,000 个节点的大图上却卡住了。
这让我发疯,我看不出它不起作用的原因,没有错误,没有堆栈溢出,只是停止了,说按任意键继续...
为如果完成了。有人知道可能出什么问题吗?
最佳答案
如documentation指定:
The highest possible limit is platform-dependent. A user may need to set the limit higher when they have a program that requires deep recursion and a platform that supports a higher limit. This should be done with care, because a too-high limit can lead to a crash.
有一个script检查该限制。
您必须实现非递归 DFS。
关于Python 递归意外停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48656094/