Finding the Exit of a Maze 373
That is easy enough. This does not solve the entire problem but it is a good stepping
stone. Good programmers always take small steps toward solutions. What should the func-
tion do if the current location is not the exit? If the current location is not the exit, then
the function checks whether it is possible to move east. If this is possible (because canMove
returns 1), then the function moves east by adding 1 to the column index and calls getOut
again. This is a recursive call. Why should the function be recursive? The reason is that we
adopt the same strategy at each cell, until the exit is found.
void getOut ( Maze * mzptr , i n t row , in t col )1
{2
i f (( mzptr -> maze )[ row ][ col ] == ’E’) // found exit3
{4
printf (" Found the exit ! n") ;5
return ;6
}7
i f ( canMove ( mzptr , row , col , EAST ))8
{9
getOut ( mzptr , row , col + 1) ;10
// moving east means adding 1 to the column index11
}12
}13
What should the function do if moving east is not possible? An example is shown in
Fig. 22.3 (a). In this case, the function tries to go south.
void getOut ( Maze * mz , i n t row , in t col )1
{2
i f (( mz -> maze )[ row ][ col ] == ’E ’) // found exit3
{4
printf (" Found the exit ! n") ;5
return ;6
}7
i f ( canMove (mz , row , col , EAST ) )8
{9
getOut (mz , row , col + 1) ;10
// moving east means adding 1 to the column index11
}12
i f ( canMove (mz , row , col , SOUTH ))13
{14
getOut (mz , row + 1 , col ) ;15
// moving south means adding 1 to the row index16
}17
}18
What is the method to determine which of the four possible directions can be taken? The
order of calling canMove determines which direction is considered first. If the order of these
calls is changed, then the function tries another direction first. The other two directions
(west and north) are also checked using the following function:
void getOut ( Maze * mzptr , i n t row , in t col )1
{2
i f (( mzptr -> maze )[ row ][ col ] == ’E’) // found exit3
{4
printf (" Found the exit ! n") ;5