algorithmgraphbreadth-first-searchdepth-first-search

Dfs Vs Bfs confusion


From a topcoder article:

"In BFS We mark a vertex visited as we push it into the queue, not as we pop it in case of DFS."

NOTE: This is said in case of dfs implementation using explicit stack.(pseudo dfs).

My question is why so? why we can not mark a vertex visited after popping from queue, instead while pushing onto the queue in case of bfs ?


Solution

  • Your confusion probably comes from thinking about trees too much, but BFS and DFS can be run on any graph. Consider for example a graph with a loop like A-B-C-A. If you go breadth-first starting from A, you will first add B and C to the list. Then, you will pop B and, unless they were marked as visited, you will add C and A to the list, which is obviously wrong. If instead you go depth first from A, you will then visit B and from there go to C and then to A, unless A was already marked as visited.

    So, in summary, you need to mark a vertex as seen as soon as you first see it, no matter which algorithm you take. However, if you only consider DAGs, you will find that things get a bit easier, because there you simply don't have any loop like the above. Anyway, the whole point is that you don't get stuck in a loop, and for that there are multiple variants. Setting a flag is one way, checking a set of visited vertices is another and in some cases like trees, you don't need to do anything but just iterate the edges in order.