Here is my algorithm for doing a BFS in pseudo code.
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.
}
}
I am struggling to implement this using recursion. Any tips?
I try:
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);
}
}
But this will fail as when a vertex has no more edges, it should go back to first edge not its last? Stuck?
Any help appreciated.