此深度优先搜索实现现在是尾递归吗?

时间:2019-03-26 14:57:19

标签: scala functional-programming tail-recursion fold

我具有此功能来遍历图形:

private def dfs(current: RCell, rCellsMovedWithEdges: Vector[RCell], acc: Vector[RCell] = Vector()): Vector[RCell] = {
    current.edges.foldLeft(acc) {
      (results, next) =>
        if (results.contains(rCellsMovedWithEdges(next))) results
        else dfs(rCellsMovedWithEdges(next), rCellsMovedWithEdges, results :+ current)
    } :+ current
  }

实施取自manuel kiessling here

这很好,但是我担心最后的“:+ current”使其成为非尾递归。

我将其更改为此:

private def dfs(current: RCell, rCellsMovedWithEdges: Vector[RCell]): Vector[RCell] = {

    @annotation.tailrec
    def go(current: RCell, rCellsMovedWithEdges: Vector[RCell], acc: Vector[RCell] = Vector()): Vector[RCell] = {
      current.edges.foldLeft(acc) {
        (results, next) =>
          if (results.contains(rCellsMovedWithEdges(next))) results
          else go(rCellsMovedWithEdges(next), rCellsMovedWithEdges, results :+ current)
      }
    }
    go(current, rCellsMovedWithEdges) :+ current
  }

但是编译器说递归调用不在尾部位置。

左手是否已经有机会进行尾递归?

如果没有,还有另一种方法可以做我想做的事吗?

2 个答案:

答案 0 :(得分:4)

这不是尾递归,因为最后一次调用不是go,而是foldLeft。由于foldLeft多次调用go,因此甚至不可能相互尾部递归。很难使DFS尾部递归,因为递归算法在很大程度上依赖于调用堆栈来跟踪您在树中的位置。如果您可以保证树很浅,我建议您不要打扰。否则,您将需要传递一个显式堆栈(List是一个不错的选择)并完全重写您的代码。

答案 1 :(得分:2)

如果要递归实现DFS,则必须从根本上手动管理堆栈:

def dfs(start: RCell, rCellsMovedWithEdges: Vector[RCell]): Vector[RCell] = {
  @annotation.tailrec
  def go(stack: List[RCell], visited: Set[RCell], acc: Vector[RCell]): Vector[RCell] = stack match {
    case Nil => acc
    case head :: rest => {
      if (visited.contains(head)) {
        go(rest, visited, acc)
      } else {
        val expanded = head.edges.map(rCellsMovedWithEdges)
        val unvisited = expanded.filterNot(visited.contains)
        go(unvisited ++ rest, visited + head, acc :+ head)
      }
    }
  }
  go(List(start), Set.empty, Vector.empty)
}

奖金:将unvisited ++ rest更改为rest ++ unvisited,您将获得BFS。