Why DFS and not BFS for finding cycle in graphs

前端 未结 9 2068
攒了一身酷
攒了一身酷 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.

提交回复
热议问题