Faster version with BFS and branch cutting.