0

这是我用伪代码执行 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);
    }
}

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

任何帮助表示赞赏。

4

1 回答 1

0

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);
   }
于 2013-03-30T03:11:45.370 回答