Why does a breadth first search use more memory than depth first?

后端 未结 3 1900
囚心锁ツ
囚心锁ツ 2021-02-02 17:47

I can\'t find an answer to this online, and in other answers to questions similar to this it just seems to be a given that an advantage of DFS is that it uses less memory than D

3条回答
  •  野的像风
    2021-02-02 18:12

    In general it may or may not depending on the particular graph.

    A depth-first search uses a stack, which contains nodes from root to the node being searched. So at most the radius of the graph.

    A breadth-first search uses a queue, which contains nodes at the front of the search. So at most all nodes at distance d.

    In general graph all you can say is that it's at most all nodes in the tree in either case.

    But if you have a balanced (or mostly so) k-ary tree, it's depth, i.e. radius, will be only O(log(n)), while the lowest layer will contain O(n) nodes (n/2 for binary tree and even more for higher degrees).

    So depth-first search will only use O(log(n)) memory and breadth-first search will use O(n). For balanced k-ary trees; for other cases different results are possible (but for most common graphs diameter will still be significantly less than circumference).

提交回复
热议问题