如何确定递归的最后一个堆栈空间

时间:2018-12-06 19:56:08

标签: python algorithm recursion graph graph-traversal

我正在通过递归实现众所周知的深度优先搜索。我想知道是否有一种方法可以知道最后一个堆栈空间中的代码。我需要这样做的原因是我不想在输出末尾添加->字符。如果可能的话,请在最后一步中'\n'

def DFS(self, vertex=None, visited=None):
    if vertex is None:
        vertex = self.root
    if visited is None:
        visited = []
        print(f"{vertex} -> ", end='')

    visited.append(vertex)
    for neighbor in self.getNeighbors(vertex):
        if neighbor not in visited:
            visited.append(neighbor)
            print(f"{neighbor} -> ", end='')
            self.DFS(neighbor, visited)

例如,它产生1 -> 2 -> 4 -> 5 ->

在相同的方法中是否还有要做?此外,我可以编写一个辅助函数来删除最后一个->字符。

@Edit:我根据@Carcigenicate的评论所做的事情

return visited # last line in DFS method
-- in main --
dfs = graph.DFS()
path = " -> ".join(str(vertex) for vertex in dfs)
print(path)

1 个答案:

答案 0 :(得分:1)

不是要对最后一个顶点进行特殊处理,而是对第一个顶点进行特殊处理。也就是说,不要试图弄清楚何时不附加“->”,而不要在第一个顶点上这样做:

def DFS(self, vertex=None, visited=None):
    if vertex is None:
        vertex = self.root
    else:
        # Not the first vertex, so need to add the separator.
        print(f" ->", end='')

    if visited is None:
        visited = []

    print(f"{vertex}", end='')

    visited.append(vertex)
    for neighbor in self.getNeighbors(vertex):
        if neighbor not in visited:
            # no need to append here, because it will be done in the recursive call.
            # and the vertex will be printed in the recursive call, too.
            # visited.append(neighbor)
            # print(f"{neighbor} -> ", end='')
            self.DFS(neighbor, visited)

这假设您的初始通话将始终为DFS(root, None, visited)。我认为这是一个合理的假设。

再三考虑,也许使用visited参数作为条件是一个更好的主意:

    if vertex is None:
        vertex = self.root

    if visited is None:
        visited = []
    else:
        # Not the first vertex, so need to add the separator.
        print(f" ->", end='')

    print(f"{vertex}", end='')

重点是,对第一个项目进行特殊案例比对最后一个项目进行特殊案例化。