# Backtracking

1. When is Backtracking: useful (what types of problem can you use it for):

• The solutions of the problem is easily recognizable
(You DO NOT have to find one easily, all you need is: if you see one, you can easily tell it's a solution)

• The problem can be solved by making stepwise improvement to a final solution

• You can undo a step made in the problem easily

The number of problems that can be solved with backtracking is very large

Backtracking is a is general purpose problem solving technique

2. General structure of a solution using backtracking:

 General structure of a Solution using Backtracking ``` public ... backtrackSolve("problem N") { if ( "problem N" is a solved problem ) { print "(solved) problem N"; // It's a solution ! return; } for ( each possible step S you can make in "problem N" ) { if ( step S is a legal move ) { Make step S (this changes "problem N" !); backtrackSolve("problem N-1"); Take step S back (this restores "problem N" !); } } } ```

The Maze solver fits into this form:

 ``` public class Maze { private int grid[][] = {{4,1,1}, {1,0,1}, {1,0,1}}; // ************************************************* // Solve a maze problem represented by "grid[][]" // starting at position (row,col) in the grid // ************************************************* public void solve(int row, int col) { if ( row == 2 && col == 2) { --> We reached the exit ! --> print solution; return; } // ***************************************** // Try all possible (but legal) steps: // ***************************************** for ( S in North, South, east, West ) { if ( OK to explore step S ) { Take step S; solve(new-row, new-col); // Problem N-1 Take step S back; } } } } ```