Why DFS and not BFS for finding cycle in graphs

前端 未结 9 2082
攒了一身酷
攒了一身酷 2020-11-30 17:25

Predominantly DFS is used to find a cycle in graphs and not BFS. Any reasons? Both can find if a node has already been visited while traversing the tree/graph.

9条回答
  •  星月不相逢
    2020-11-30 18:05

    1. DFS is easier to implement
    2. Once DFS finds a cycle, the stack will contain the nodes forming the cycle. The same is not true for BFS, so you need to do extra work if you want to also print the found cycle. This makes DFS a lot more convenient.

提交回复
热议问题