Optimized bfs