Fixed BFS algorithm