Solve with Backtracking
Try a path forward. If you hit a dead end, go back to the last choice and try another option.
- Describe backtracking as try, fail, undo, try again
- Mark visited squares to avoid loops
- Relate maze solving to search trees
Finish first
Topic contents
Lesson 1 of 3
Dead ends are information
In a maze, walking until you hit a wall is not failure. It tells you that path does not work. You step back to the last junction and pick a different turn.
That step back is backtracking. Computers use it for puzzles, games and planning routes.
Use the maze solver lab. Watch the explorer mark tried paths, retreat when blocked, and try another branch.
Maze solver
Watch an explorer try paths, mark dead ends, backtrack and eventually reach the goal.
Maze solver
Try, backtrack, try againStart
You are at S. Try a direction. If it is a wall, back up and try another way.
Lesson 2 of 3
Remember where you have been
Without memory you might walk in circles forever. Mark cells you already tried so you do not repeat the same mistake.
A stack of choices helps. Push each junction you enter. Pop when you backtrack. The top of the stack is where you try the next option.
You will meet stacks again in later CS topics. Here they are just a pile of places to revisit.
Lesson 3 of 3
When to use backtracking
Backtracking fits puzzles with many choices and clear dead ends: sudoku, word searches in a letter grid, or finding a path through a maze when the first try hits a wall.
It can be slow if choices explode, but it is easy to understand and often good enough for small cases.
Next you will plan on paper before typing any code, combining break-down, trace and search habits.
Practice
Work these out yourself
No answer key here on purpose: these are the questions worth thinking through before you move on. Open one and work it out.
0/3 attemptedAssessment
Check your understanding
Answer each question, then read the explanation. That is where the learning is.
Finished this topic?
0 of 3 lessons marked done. Marking the topic complete ticks the rest.
