Python DFS的最佳实现
我正在Python3上实现DFS算法,我的实际代码是Python DFS的最佳实现,python,algorithm,global-variables,graph-theory,Python,Algorithm,Global Variables,Graph Theory,我正在Python3上实现DFS算法,我的实际代码是 def util_DFS(G, i, startTime, globalStartTime): """ Util function used in DFS :param G: (networkx.DiGraph) Graph on wich will be applied the DFS algorithm :param i: Integer representing the vertex from which DFS
def util_DFS(G, i, startTime, globalStartTime):
"""
Util function used in DFS
:param G: (networkx.DiGraph) Graph on wich will be applied the DFS algorithm
:param i: Integer representing the vertex from which DFS will be applied
:param startTime: global variable containing an array recording the time needed to reach each vertex
:param globalStartTime: global variabl recording the number of nodes visited
"""
startTime[i] = globalStartTime
globalStartTime += 1
for j in G.neighbors(i):
if startTime[j] == -1:
util_DFS(G, j, startTime, globalStartTime)
def DFS(G, i):
"""
:param G: (networkx.DiGraph) Graph on wich will be applied the DFS algorithm
:param i: Integer representing the vertex from which DFS will be applied
"""
startTime = np.zeros(len(G), dtype=np.int64) - 1
globalStartTime = 0
util_DFS(G, i, startTime, globalStartTime)
return startTime
代码运行良好,给出了我们等待的结果,但我想知道是否有更好的方法来编写DFS,一种不需要像我所做的那样使用两个函数的方法
请注意,第二个函数
DFS
只是util\u DFS
的包装。我需要这样一个包装器,因为变量startTime
和globalStartTime
需要是全局的,如果图形断开连接,这将不起作用,请您解释一下,这是因为如果没有达到某个弧,递归将无限继续吗?我刚刚检查了一个断开连接的图,它工作得很好,如果图断开连接,每个节点都不会到达。只有包含起始节点(启动dfs的位置)的组件才会被探索,因为您有工作代码,并且要求“更好”,所以这个问题更适合您。