Updated BFS algorithm