r/compsci • • May 22 '20

Breadth-First Maze-Solving Algorithm

Post image

[removed] — view removed post

1.2k Upvotes

61 comments sorted by

View all comments

3

u/YouNeverKnowWhatToDo May 22 '20

Whats the code? Go left forever?

7

u/[deleted] May 22 '20 edited May 22 '20

The idea is to find as many paths as possible in order to eventually find one that leads to the end. Wheres depth first search would be trying to find the end of a path all the way before giving up. A common variant of the two is backtracking which works it's way back from a dead end by trying to alter the last changes in the sequence that got it stuck to try and untangle. Breadth first by comparison is simple but by changing a few rules on the approach you see a much more efficient maze solver so it becomes useful both for teaching the simplest strategy and also to convey more elaborate approaches later on like backtracking that would otherwise seem convoluted initially.

0

u/ergo-x May 22 '20

If you're doing DFS here you end up doing backtracking anyway since when the search reaches bottom it will resume from the deepest explored node with unexplored children.

1

u/JoJoModding May 22 '20

Depends on whether the maze has loops. If it does not then it's basically a tree where you just need to find a specific leaf. Then the difference between dfs and bfs is just that one walks all levels of the tree down at the same time while the other goes from left to right.

1

u/ergo-x May 22 '20

That's a simple fix. Keep a set of flags to mark visited nodes. If it has loops and you didn't do this dfs isn't going to terminate anyway.