14

I have read about DFS and BFS many times but I have this doubt lingering my mind since long. In a lot of articles it is mentioned that DFS can get stuck in infinite loops.

As far as I know, this limitation can easily be removed by keeping track of the visited nodes. In fact, in all the books that I have read, this little check is a part of DFS.

So why are 'infinite loops' mentioned as a disadvantage of DFS? Is it just because the original DFS algorithm did not have this check for visited nodes? Please explain.

Rob
  • 5,223
  • 5
  • 41
  • 62
vjain27
  • 3,514
  • 9
  • 41
  • 60

3 Answers3

26

(1) In graph search algorithms [used frequently on AI], DFS's main advantage is space efficiency. It is its main advantage on BFS. However, if you keep track of visited nodes, you lose this advantage, since you need to store all visited nodes in memory. Don't forget the size of visited nodes increases drastically over time, and for very large/infinite graphs - might not fit in memory.

(2) Sometimes DFS can be in an infinite branch [in infinite graphs]. An infinite branch is a branch that does not end [always has "more sons"], and also does not get you to your target node, so for DFS, you might keep expanding this branch inifinitely, and 'miss' the good branch, that leads to the target node.

Bonus:
You can overcome this flaw in DFS, while maintaining relatively small memory size by using a combination of DFS and BFS: Iterative Deepening DFS

amit
  • 175,853
  • 27
  • 231
  • 333
  • For the issue #1: I wonder whether keeping ONLY the nodes of the branch currently being searched can avoid loops in DFS too? Whenever a node is chosen to be expanded, if it's on that list we can skip it. This way we don't need to keep track of all the visited nodes thus not much overhead. Right? For issue #2: I agree this is one of the main disadvantages of the DFS(Although the bigger disadvantage of it is indeed its "uninformed" exploration, I know you didn't mention that since it's irrelevant to the question. Just saying for curious readers). – M-J Nov 25 '18 at 13:56
3

a conventional DFS algorithm does track down nodes. A local search algorithm does not track down states and behaves with amnesia. So I think the loop mainly refers to the one an infinite branch(a branch with infinite possible states). In that case, DFS simply goes down and become too focused on one branch.

Strin
  • 677
  • 9
  • 15
0

If you do not check for cycles, then DFS can get stuck in one and never find its target whereas BFS will always expand out to all nodes at the next depth and therefore will eventually find its target, even if cycles exist.

Put simply:
If your graph can have cycles and you're using DFS, then you must account for cycles. On the other hand, BFS provides the option to ignore cycles at the expense of efficiency, which is often acceptable when searching a small number of nodes.

gMale
  • 17,147
  • 17
  • 91
  • 116