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.
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.