breadth first or depth first search

后端 未结 4 501
抹茶落季
抹茶落季 2021-02-04 17:09

I know how this algorithm works, but cant decide when to use which algorithm ?

Are there some guidelines, where one better perform than other or any considerations ?

4条回答
  •  囚心锁ツ
    2021-02-04 17:50

    If you are traversing a tree, depth-first will use memory proportional to its depth. If the tree is reasonably balanced (or has some other limit on its depth), it may be convenient to use recursive depth-first traversal.

    However, don't do this for traversing a general graph; it will likely cause a stack overflow. For unbounded trees or general graphs, you will need some kind of auxiliary storage that can expand to a size proportional to the number of input nodes. In this case, breadth-first traversal is simple and convenient.

    If your problem provides a reason to choose one node over another, you might consider using a priority queue, instead of a stack (for depth-first) or a FIFO (for breadth-first). A priority queue will take O(log K) time (where K is the current number of different priorities) to find the best node at each step, but the optimization may be worth it.

提交回复
热议问题