better bfs implementation