Why DFS and not BFS for finding cycle in graphs

前端 未结 9 2036
攒了一身酷
攒了一身酷 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:04

    You'll have to use BFS when you want to find the shortest cycle containing a given node in a directed graph.

    Eg:

    If the given node is 2, there are three cycles where it is part of - [2,3,4], [2,3,4,5,6,7,8,9] & [2,5,6,7,8,9]. Shortest is [2,3,4]

    For implementing this using BFS, you have to explicitly maintaining the history of visited nodes using proper data structures.

    But for all other purposes (eg: to find any cyclical path or to check if a cycle exists or not), DFS is the clear choice for reasons mentioned by others.

    0 讨论(0)
  • 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.
    0 讨论(0)
  • 2020-11-30 18:05

    To prove that a graph is cyclic you just need to prove it has one cycle(edge pointing towards itself either directly or indirectly).

    In DFS we take one vertex at a time and check if it has cycle. As soon as a cycle is found we can omit checking other vertices.

    In BFS we need to keep track of many vertex edges simultaneously and more often than not at the end you find out if it has cycle. As the size of the graph grows BFS requires more space, computation and time compared to DFS.

    0 讨论(0)
提交回复
热议问题