12

While reading about DFS vs BFS, I came across a statement that DFS is faster than BFS, and requires less memory.

My implementation is in C++ for both, making a stack for DFS and queue for BFS. Can someone please explain what, and how are the speed and memory requirements different?

Dominique Fortin
  • 2,212
  • 15
  • 20
  • 3
    A blanket statement that DFS is faster than BFS and requires less memory is just wrong. Please provide a reference. The truth, as with many things in computer science, is "it depends on the graph." – Jim Mischel Nov 10 '17 at 17:55

1 Answers1

20
  • Memory requirements: The stack size is bound by the depth whereas the queue size is bound by the width. For a balanced binary tree with n nodes, that means the stack size would be log(n) but the queue size would b O(n). Note that an explicit queue might not be needed for a BFS in all cases -- for instance, in an array embedded binary tree, it should be possible to compute the next index instead.

  • Speed: I don't think that's true. For a full search, both cases visit all the nodes without significant extra overhead. If the search can be aborted when a matching element is found, BFS should typically be faster if the searched element is typically higher up in the search tree because it goes level by level. DFS might be faster if the searched element is typically relatively deep and finding one of many is sufficient.

Stefan Haustein
  • 18,427
  • 3
  • 36
  • 51
  • 2
    Under memory requirements you say, "an explicit queue might not be needed for a DFS in all cases." It's unclear to me here whether you're talking about DFS or BFS, because DFS doesn't require a queue at all. Also, your discussion here is limited to trees, whereas the OP's question is about graphs in general. The memory requirement depends on the relative width and height of the graph. – Jim Mischel Nov 10 '17 at 17:51
  • He mentioned BFS not DFS – user1463110 Mar 14 '19 at 21:12
  • @Stefan explained it well, just adding another highlight from Speed perspective : BFS might be a little slower because it uses two operations on Queue , enque and deque at each node visit. This is a bit extra processing , although O(1) order, but still extra compare to DFS node visit. – Dhrubo Oct 05 '20 at 07:22
  • Could you elaborate more about the statement under __Mem. Req.__: *Note that an explicit queue might not be needed for a BFS in all cases -- keeping a stack of child indices might be sufficient where feasible.*? – NeoZoom.lua Dec 28 '20 at 07:25
  • Not sure what exactly I was referring to -- I think basically one needs a O(1) mapping from the index to node. I have replaced this fragment with a concrete example. – Stefan Haustein Dec 28 '20 at 13:39