Why DFS and not BFS for finding cycle in graphs

前端 未结 9 2087
攒了一身酷
攒了一身酷 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 17:40

    It sort of depends if you are talking about recursive or iterative implementations.

    Recursive-DFS visits every node twice. Iterative-BFS visits every node once.

    If you want to detect a cycle, you need to investigate the nodes both before and after you add their adjacencies -- both when you "start" on a node and when you "finish" with a node.

    This requires more work in Iterative-BFS so most people choose Recursive-DFS.

    Note that a simple implementation of Iterative-DFS with, say, std::stack has the same problem as Iterative-BFS. In that case, you need to place dummy elements into the stack to track when you "finish" working on a node.

    See this answer for more details on how Iterative-DFS requires additional work to determine when you "finish" with a node (answered in the context of TopoSort):

    Topological sort using DFS without recursion

    Hopefully that explains why people favor Recursive-DFS for problems where you need to determine when you "finish" processing a node.

提交回复
热议问题