Use deque instead of list for BFS (#91139)
Using list with `pop(0)` makes the search running time quadratic instead of linear.
Pull Request resolved: https://github.com/pytorch/pytorch/pull/91139
Approved by: https://github.com/ZainRizvi, https://github.com/huydhn, https://github.com/seemethere, https://github.com/malfet