I watched a video for BFS from MIT and the algorithm the lecturer presented was really complicated compared to what I came up. My solution seems to work fine and walk through the vertices in the correct order. Am I missing something?
public static void BFS(GraphNode currentNode, GraphNode searchedNode) { if (currentNode.index == searchedNode.index) { System.out.println("Found!"); return; } if (visited[currentNode.index]) { return; } visited[currentNode.index] = true; for (GraphNode child : currentNode.children) { if (!visited[child.index]) { nodeQueue.add(child); } } if (!nodeQueue.isEmpty()) { BFS(nodeQueue.poll(), searchedNode); } }
One drawback is that it keeps running after finding a node, but that could be fixed easily by clearing the queue when element is found.