Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are you guaranteed to find your result if it is in the graph with BFS but not with DFS?

I've read somewhere that DFS is not gaurenteed to find a solution while BFS is.. why? I don't really get how this is true.. could someone demonstrate a case for me that proves this?

like image 843
Skizit Avatar asked Dec 11 '10 12:12

Skizit


People also ask

What problem can BFS solve whilst Depth First Search DFS Cannot?

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.

Does DFS guarantee solution?

DFS cannot always guarantee that the solution will be found 2. DFS algorithms conduct searches by exploring the graph one layer at a time 3. BFS always finds optimal solution 4.

Do BFS and DFS always give same different result?

Provided that your DFS always traverses the left node first, then your BFS and DFS will be the same. You can extend this logic to any type of tree. If every node has at most one child that also has children, then your DFS and BFS will be the same if in the DFS you always traverse the nodes without children first.

What is the reason of traversal of a graph using BFS or DFS is different from binary tree traversal?

BFS can be used to find a single source shortest path in an unweighted graph because, in BFS, we reach a vertex with a minimum number of edges from a source vertex. In DFS, we might traverse through more edges to reach a destination vertex from a source.


1 Answers

DFS, since its a Depth first search, could get stuck in an infinite branch and never reach the vertex you're looking for. BFS goes through all vertices at the same distance from the root each iteration, no matter what branch they're on so it will find the desired vertex eventually.
example:

root -> v1 -> v2 -> v3 -> ... goes on forever
|-> u.

in this example, if DFS begins at the root and then goes on to v1. it will never reach u since the branch it entered is infinite. BFS will go from root to either v1 or u and then to the other.

like image 195
yurib Avatar answered Nov 15 '22 06:11

yurib