Finding the Exit of a Maze 361
Move to (3,19)
Move to (2,19)
Move to (1,19)
Move to (2,19)
Move to (3,19)
Move to (4,19)
Move to (5,19)
Column 19 is the corridor at the right end of the maze. The top of this corridor is cell
(1, 19). After reaching this cell, you discover that it is a dead end. Then you have to turn
around and continue the search for the exit. This is called backtracking. As a result, the
coordinates (2, 19), (3, 19), . . . , are repeated showing backtracking.
This chapter provides an opportunity using several topics covered in this book so far:
• Reading data from a file.
• Creating a structure to hold the data of the maze.
• Allocating memory to store the maze cells.
• Using recursion to move around the maze and find the exit.
22.2 Reading the Maze File
A maze file uses four characters to represent bricks, corridors, the exit, and the starting
point. In addition, each line ends with a new line character (i.e., ’n’). Fig. 22.1 is an example
of a maze file. The following program reads a maze file and prints some information about
it. The information includes:
• The number of rows and the number of columns in the maze. The maze must be
rectangular, i.e., all rows have the same number of columns.
• The location (row, column) of the exit.
• The location (row, column) of the starting point.
Please remember that the coordinate of the upper left corner is (0, 0). Moving right
increases the column, and moving down increases the row.
/* read a maze file , print the size , the c oordinate s of1
the exit and the starting point . */2
#in clude < stdio .h >3
#in clude < stdlib .h >4
int main ( i n t argc , char * * argv )5
{6
FILE * fptr ;7
int ch ;8
int row = 0;9
int column = 0;10
int numberB rick = 0;11
int exitRow , ex itColumn ;12
int startRow , startC olumn ;13
int number Column ;14
i f ( argc < 2)15
{16
printf (" Need to provide the file ’s name . n") ;17