【问题标题】:Is is possible to implement BFS using recursion? [duplicate]是否可以使用递归来实现 BFS? [复制]
【发布时间】:2013-03-30 00:41:13
【问题描述】:

这是我用伪代码执行 BFS 的算法。

public void bfs_usingQueue() {
    Queue<Vertex> queue = ...
    // 1. visit root node
    ...
    // 2. Put root vertex on queue
    ...
    while(!queue.isEmpty()) {
        // 3. Get the vertex at top of cue 
        // 4. For this vertex, get next unvisited vertex 
        // 5. Is there is an unvisited node for this vertex?
             // 5a. Yes.
             // 5b. Visit it.
             // 5c. Now add it to que. 
        // 6. No there is not one unvisited node for this vertex.
             // 6a. Pop current node from que as it has no other unvisited nodes.
    }

}

我正在努力使用递归来实现这一点。有什么建议吗?

我试试:

private void bfs_recursion() {
    // begin with first vertex
    bfs_recursion(vertexes[0]);
}


private void bfs_recursion(Vertex vertex) {
    // visit first
    visitVertex(vertex);

    // get next unvisitedVertex 
    Vertex unvisitedVertex = ...
    if (unvisitedVertex != null) {
        visitVertex(unvisitedVertex);
        bfs_recursion(vertex);
    } else {
        bfs_recursion(unvisitedVertex);
    }
}

但这会失败,因为当顶点没有更多边时,它应该回到第一个边而不是最后一个? 卡住了?

任何帮助表示赞赏。

【问题讨论】:

    标签: java algorithm


    【解决方案1】:

    您可以让bfs_recursion() 也采用顶点索引参数,例如,-1 表示“处理父级,而不是子级”:

    private void bfs_recursion(Vertex vertex, int index) {
       if (index==-1) {
          visitVertex(vertex);
          bfs_recursion(vertex, 1);
       } else {
          visitVertex(getChild(index));
          bfs_recursion(vertex+1);
       }
    

    【讨论】:

      猜你喜欢
      • 2012-04-12
      • 1970-01-01
      • 1970-01-01
      • 2012-01-22
      • 2013-08-13
      • 1970-01-01
      • 2012-11-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多