Skip to content

Solve with Backtracking

Try a path forward. If you hit a dead end, go back to the last choice and try another option.

Class 9 to 10beginner20 min3 lessons1 interactive lab
By the end you will be able to
  • Describe backtracking as try, fail, undo, try again
  • Mark visited squares to avoid loops
  • Relate maze solving to search trees

Finish first

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.

Interactive lab

Maze solver

Watch an explorer try paths, mark dead ends, backtrack and eventually reach the goal.

Maze solver

Try, backtrack, try again
S
G
1 / 8

Start

You are at S. Try a direction. If it is a wall, back up and try another way.

Continue

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.

Continue

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.

Continue

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 attempted

Assessment

Check your understanding

Answer each question, then read the explanation. That is where the learning is.

0/4
  1. Question 1: Backtracking means what?
    Question 1 / 4

    Backtracking means what?

    Select an option first
  2. Question 2: Why mark visited cells?
    Question 2 / 4

    Why mark visited cells?

    Select an option first
  3. Question 3: A dead end tells you what?
    Question 3 / 4

    A dead end tells you what?

    Select an option first
  4. Question 4: A stack of junctions helps because what?
    Question 4 / 4

    A stack of junctions helps because what?

    Select an option first
4 of 4 questions left.

Finished this topic?

0 of 3 lessons marked done. Marking the topic complete ticks the rest.