Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

breadth first or depth first search

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 ?

Thanks very much.

like image 593
newcoderintown Avatar asked May 12 '10 19:05

newcoderintown


People also ask

Is depth-first or breadth-first better?

BFS is more suitable for searching vertices closer to the given source. DFS is more suitable when there are solutions away from source. 8. BFS considers all neighbors first and therefore not suitable for decision-making trees used in games or puzzles.

Why depth-first traversal better than breadth-first?

BFS can be used to find the shortest path, with unit weight edges, from a node (origional source) to another. Whereas, DFS can be used to exhaust all the choices because of its nature of going in depth, like discovering the longest path between two nodes in an acyclic graph.

Which is better Breadth-first search or best-first search?

Best-first search is informed whereas Breadth-first search is uninformed, as in one has a metal detector and the other doesn't! Breadth-first search is complete, meaning it'll find a solution if one exists, and given enough resources will find the optimal solution.

Is depth-first search best-first search?

Best-first search (BFS) expands the fewest nodes among all admissible algorithms using the same cost function, but typically requires exponential space. Depth-first search needs space only linear in the maximum search depth, but expands more nodes than BFS.


2 Answers

If you want to find a solution with the shortest number of steps or if your tree has infinite height (or very large) you should use breadth first.

If you have a finite tree and want to traverse all possible solutions using the smallest amount of memory then you should use depth first.

If you are searching for the best chess move to play you could use iterative deepening which is a combination of both.

IDDFS combines depth-first search's space-efficiency and breadth-first search's completeness (when the branching factor is finite).

like image 69
Mark Byers Avatar answered Sep 21 '22 19:09

Mark Byers


BFS is generally useful in cases where the graph has some meaningful "natural layering" (e.g., closer nodes represent "closer" results) and your goal result is likely to be located closer to the starting point or the starting points are "cheaper to search".

When you want to find the shortest path, BFS is a natural choice.

If your graph is infinite or pro grammatically generated, you would probably want to search closer layers before venturing afield, as the cost of exploring remote nodes before getting to the closer nodes is prohibitive.

If accessing more remote nodes would be more expensive due to memory/disk/locality issues, BFS may again be better.

like image 32
Uri Avatar answered Sep 22 '22 19:09

Uri