Backtracking Algorithms
Backtracking Algorithms
Backtracking Algorithms
1
Example: Solving a maze
by recursive backtracking
The only valid moves through the maze are in the four primary
directions: up, down, right and left. No diagonal moves are
allowed. The starting location and the exit are given. In this
example the maze is 12 rows by 12 columns, however the maze
can be any size.
2
Finding a recursive approach
The two stopping cases for this problem are:
1. If the current square is the exit location, the maze is solved,
return 1.
2. If the current square is marked, or a wall, or outside the
maze, return 0.
Algorithm
3. Otherwise,
Change the grid entry‘.’ to ‘x’, marking this location as
visited so that later we don’t retrace our steps.
Search for a solution in each of the primary directions:
If no direction from the current location yields a correct
solution, then there is no path from this location, and
mazeTraverse returns 0.
If a solution is found starting from the current location
in any one of the directions, then grid entry is changed
to a ‘-‘, and mazeTraverse returns 1.
3
The C code:
/* Function: valid
* This function returns false if the current
* cell location [i][j] is outside the maze
* or it is a wall or an already marked.
* Otherwise it considers the cell as a
* valid move and returns 1.
*/
int i, int j)
{
int flag = 1;
if (i < 0 || i >=rows || j<0 || j>=cols)
flag = 0;
if (flag && (maze[i][j]=='#' || maze[i][j]=='x'))
flag = 0;
return flag;
}
4
/* Function maze_traverse
* This function attempts to generate a solutionto
* the current maze from point [si,sj]. It returns
* true if the maze has a solution and false
* otherwise. The implementation uses recursion to
* solve the new mazes that result from marking the
* current cell and moving up one step along each
* open passage. Possible paths are tried in the
* primary directions in this order: north, east,
* south, west.
*/
int maze_traverse(char maze[][MAXSIZE], int rows,
int cols, int si, int sj, int ei, int ej)
{
int done,c ;
if (!done)
done = maze_traverse(maze,rows,cols,si,
sj+1, ei, ej);
if (!done)
done = maze_traverse(maze, rows, cols,
si+1, sj, ei,ej);
if (!done)
done = maze_traverse(maze, rows, cols, si,
sj-1,ei,ej);
if (done)
maze[si][sj] = '-';
return done;
}
5
}
6
0 1 2 3 4 5 6 7 8 9 10 11
0 # # # # # # # # # # # #
1 # . . . # . . . . . . #
2 . . # . # . # # # # . #
3 # # # . # . . . . # . #
4 # . . . . # # # . # . .
5 # # # # . # . # . # . #
6 # . . # . # . # . # . #
7 # # . # . # . # . # . #
8 # . . . . . . . . # . #
9 # # # # # # . # # # . #
10 # . . . . . . # . . . #
11 # # # # # # # # # # # #