Search code examples
algorithmgraphdepth-first-searchbreadth-first-searchtraversal

Is BFS and DFS Guaranteed To Find The Shortest Path For a Given Graph?


Wondering, if for given G graph, considering cost of the edges are labeled. Not specifying whether they are the same for each edge, or not. Is BFS or DFS known to find the shortest path using the standard implementation for both?

I'm expecting that they can find it, but they are not always not known for it.


Solution

  • In a BFS, each path probes deeper by one, then moves on to the next path. Therefore when the correct node is found, all paths have the same length (except for those that haven't been incremented yet). Because of this there isn't a shorter way to reach the node.

    For DFS imagine a graph like a clock where every hour is connected to its adjacent hours, if we start at 12 and DFS for 11 starting with 1 we will probe through every single hour until we reach 11.

    So BFS will find the shortest path, DFS won't necessarily.

    BFS Visualization

    DFS Visualization