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

后端 未结 3 1898
囚心锁ツ
囚心锁ツ 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:14

    Either search method can be written so that it only has to keep track of the previous node, but then the DFS is more efficient than the BFS.

    The DFS only has to travel one level at a time to find out if there are more nodes nearby. It would move through the nodes in this order to search trough all of them:

    8-3-1-3-6-4-6-7-6-3-8-10-14-13-14-10-8
    

    The BFS has to travel up and down the tree all the way to the top whenever it goes to the other half of the tree. It would move through the nodes in this order:

    8-3-8-10-8-3-1-3-6-3-8-10-14-10-8-3-1-6-4-6-7-6-3-8-10-14-13-14-10-8
    

    (I'm not certain if that is complete though, perhaps it even has to travel up and down a few more times to find out that there are no more nodes on the last level.)

    As you see, the BFS is a lot less efficient if you want to implement an algorithm that uses a minimum of memory.

    If you want to use more memory to make the algorithms more efficient, then they end up having roughly the same efficiency, basically only going through each node once. The DFS needs less memory as it only has to keep track of the nodes in a chain from the top to the bottom, while the BFS has to keep track of all the nodes on the same level.

    For example, in a (balanced) tree with 1023 nodes the DFS has to keep track of 10 nodes, while the BFS has to keep track of 512 nodes.

提交回复
热议问题