# Intro to Backtracking

1. Backtracking:

• is a recursive EXHAUSTIVE SEARCH technique

2. Exhaustive search:

• is a "dumb" problem solving technique whereby EVERY POSSIBLE solution is examined.

• Due to the speed of the computer, this simple problem solving technique can be useful if the total number of cases that need to be examined is reasonably small (billions)

3. Problem description: find all paths that lead from a starting point to a ending point through a maze

Example: how do you find paths through a maze... trial & error

4. Prime Directive in Searching:

• Never "double back"

• In other words: DO NOT re-visit a position (that you have already visited) with the intension to search further from that position...

This will lead to infinite loop

NOTE: it is OK to re-visit an old position with the intension to search in ANOTHER direction

5. Finding paths through a maze using a computer:

• First, we need to representing the maze using something that the computer will understand:

• 0 means wall (you CANNOT pass)
• 1 means corridor (you can pass)

• Second, notice that we need to remember the places that we have visited

Otherwise, we will double back and the program will loop indefinitely.

Solution:

• 0 means wall (you CANNOT pass)
• 1 means corridor that we have not yet visited
• 4 means corridor that we have ALREADY visited

• Finally, we need to know our current progress in the maze

6. How the program will work: (Visit order is: N, S, E, W)

 ``` ```

7. The Maze Solver Program:

 ``` public class Maze { private int grid[][] = {{4,1,1}, // Defines a 3x3 integer array {1,0,1}, // - represents the initial position {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: // ***************************************** if ( OK to explore N ) { Walk to N; solve(row-1, col); // (row-1,col) is coordinate of Northern square TAKE STEP BACK; } if ( OK to explore S ) { Walk to S; solve(row+1, col); // (row+1,col) is corrdinate of Southern square TAKE STEP BACK; } if ( OK to explore E ) { Walk to E; solve(row, col+1); // (row,col+1) is corrdinate of Eastern square TAKE STEP BACK; } if ( OK to explore W ) { Walk to W; solve(row, col-1); // (row,col-1) is corrdinate of Western square TAKE STEP BACK; } } } ```