refactor bfs algorithm