3. A Mazing Problem
• A nice application of stacks
• Representation of Maze
– Two dimensional array
•
•
Zero : the open path
One : the barriers
An example maze
4. A Mazing Problem(Cont’d)
• m x p maze
– Need an (m+2) x (p+2) array
– For border of maze
– Entrance : 1, 1
– Exit : m, p
• If X marks the spot of our current location
Allowable moves
5. A Mazing Problem(Cont’d)
• Offset
Class Offset{
int vert;
int horiz;
}
Name
Dir
move[dir].vert
move[dir].horiz
N
NE
E
SE
S
SW
W
NW
0
1
2
3
4
5
6
7
-1
-1
0
1
1
1
0
-1
0
1
1
1
0
-1
-1
-1
Table of moves
next_row = row + move[dir].vert;
next_col = col + move[dir].horiz;
6. A Mazing Problem(Cont’d)
• Checked position
– Changing mark[row][col] to 1 after visit a position, maze[row][col]
Class Element{
int row;
int col;
int dir;
}
7. A Mazing Problem(Cont’d)
• Initial maze algorithm
Initialize a stack to the maze’s entrance coordinates and direction to north;
While(stack is not empty){
/* move to position at top of stack */
<row, col, dir> = delete from top of stack;
while(there are more moves from current postion){
<next_row, next_col> = coordinates of next move;
dir = directional of move;
if((next_row == EXIT_ROW) && (next_col == EXIT_COL))
success;
if(maze[next_row][next_col] == 0 &&
mark[next_row][next_col] == 0){
/*legal move and haven’t been there */
mark[next_row][next_col] = 1;
/* save current position and direction */
add<row, col, dir> to the top of the stack;
row = next_row;
col = next_col;
dir = north;
}
}
}
Print(“No path found”);