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