How do we know whether we need to use BSF or DSF algorithm?

Technology CommunityCategory: Graph TheoryHow do we know whether we need to use BSF or DSF algorithm?
VietMX Staff asked 3 years ago

First think about:

  • BSF searches for siblings first. DFS obviously searches for children first. So relationship type searches across fields would probably lend itself to BFS, where hierarchical (trees, folders, ranks, etc) would be more suited as a DFS.
  • BFS is going to use more memory depending on the branching factor (O(branchingFactor^maxDepth)), however, BFS is a complete algorithm meaning if you are using it to search for something in the lowest depth possible, BFS will give you the optimal solution.
  • BFS space complexity is O(b^d), the branching factor raised to the depth (can be a lot of memory).
  • DFS on the other hand, is much better about space however it may find a suboptimal solution. Meaning, if you are just searching for a path from one vertex to another, you may find the suboptimal solution (and stop there) before you find the real shortest path. DFS space complexity is O(|V|)… meaning that the most memory it can take up is the longest possible path (the radius of the graph).
  • The time complexity for both is O(b^d) meaning it is based on the branching factor and the depth searched. BFS and DFS have the same worst case that is searching the entire tree.
  • In terms of implementation, BFS is usually implemented with Queue, while DFS uses a Stack.

Some other considerations you may apply:

  • If you know a solution is not far from the root of the tree, a breadth first search (BFS) might be better.
  • If the tree is very deep and solutions are rare, depth first search (DFS) might take an extremely long time, but BFS could be faster.
  • If the tree is very wide, a BFS might need too much memory, so it might be completely impractical.
  • If solutions are frequent but located deep in the tree, BFS could be impractical.
  • If the search tree is very deep you will need to restrict the search depth for depth first search (DFS), anyway (for example with iterative deepening).