这是我用伪代码执行 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);
}
}
但这会失败,因为当一个顶点没有更多边时,它应该回到第一个边而不是最后一个?卡住?
任何帮助表示赞赏。