Intro to Backtracking

  1. Backtracking:

  2. Exhaustive search:

  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:

    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:

  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;
    	  }
           }
        }