0

tldr; You start at 3 and want to end up at 4. There is always a guaranteed path. You can only hop onto 1's. You move like a knight, m units in one direction, and n units in another, every time. What is the least number of hops to get to your destination.

Input:
1 2
1 0 1 0 1
3 0 2 0 4
0 1 2 0 0
0 0 0 1 0

You start at 3 and hop to the 1 at the middle top, then to 4. Each hop is 1 unit in 1 direction and 2 units in another. Thus, the answer for this case is 2. Why is BFS better than DFS in this situation?

Bob Wang
  • 63
  • 4

1 Answers1

0

Breadth-first search is guaranteed to find the shortest path from the start to the goal, while depth-first search isn’t.

templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065
  • why? The solution says it was something to do with DFS following dead ends over and over again, but I'm not sure why? – Bob Wang Apr 24 '20 at 00:56
  • I would say this is less of an efficiency issue and more of a correctness issue. BFS is guaranteed to always find the shortest path, since it expands out paths in increasing order of distance. DFS will find *some* path to the goal, but not necessarily the best path. You can also do a “DFS-like” algorithm of enumerating every possible path and taking the shortest, but that’s strictly worse than the other two approaches. – templatetypedef Apr 24 '20 at 06:30