Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shortest path: DFS, BFS or both?

Tags:

I know BFS alone can find the shortest path in an unweighted graph but I also read on a couple of sites where people were claiming that either BFS or DFS could do this. I just wanted to confirm that these were probably mistakes and that only BFS can do this (I wasn't completely confident even after doing a quick google search). If I'm incorrect, can someone please explain how it's possible for DFS to give shortest path.

like image 909
user1136342 Avatar asked Feb 09 '13 03:02

user1136342


People also ask

Is shortest path BFS or DFS?

BFS(Breadth First Search) uses Queue data structure for finding the shortest path. DFS(Depth First Search) uses Stack data structure. 3. BFS is a traversal approach in which we first walk through all nodes on the same level before moving on to the next level.

Why DFS is not used for shortest path?

Assign edges (s,t) and (s,a) weights such that the rule chooses to visit a first, and assign (a,b) a weight greater than the one of (s,t). Therefore, it is plausible that DFS can never find shortest paths (in general graphs).


1 Answers

DFS does not necessarily yield shortest paths in an undirected graph. BFS would be the correct choice here.

As an example, consider a graph formed by taking the corners of a triangle and connecting them. If you try to find the shortest path from one node to another using DFS, then you will get the wrong answer unless you follow the edge directly connecting the start and destination nodes.

As @nhahtdh notes below, there’s a variant of DFS called iterative deepening in which you run DFS with a maximum depth of one, then two, then three, etc. until you find your target. This will always find the shortest path, and does so using less memory than BFS.

Hope this helps!

like image 112
templatetypedef Avatar answered Sep 18 '22 21:09

templatetypedef