376 Intermediate C Programming
i f ( canMove ( mzptr , row , col , WEST ) && ( dir != EAST ))18
{19
getOut ( mzptr , row , col - 1, WEST );20
}21
i f ( canMove ( mzptr , row , col , NORTH ) && ( dir != SOUTH ))22
{23
getOut ( mzptr , row - 1, col , NORTH );24
}25
}26
This function prevents going back and forth by checking whether the previous step was
in the opposite direction.
The function does not turn around after reaching a dead end. It needs a way to distin-
guish between “forward” and “backward” mode. In forward mode, it does not revisit cells.
In backward mode after turning around, it is necessary to revisit cells.
What does a dead end mean? It means that none of the four forward directions are
available. In other words, all the four if (canMove ...&& (dir != ...)) conditions are
false. Why? If one of them were true, then the function would have taken that direction
and moved forward. Thus, if the function reaches the bottom without calling itself, the cell
is a dead end. The mode variable is set to BACKWARD. It must be a pointer in order to keep
this change when the function returns to the caller after the top frame is popped.
void getOut ( Maze * mzptr , i n t row , in t col ,1
int dir , int * mode )2
{3
i f (( mzptr -> maze )[ row ][ col ] == ’E’)4
{5
printf (" Found the exit ! n") ;6
return ;7
}8
i f ( canMove ( mzptr , row , col , EAST ) && ( dir != WEST ))9
{10
getOut ( mzptr , row , col + 1 , EAST , mode );11
}12
i f ( canMove ( mzptr , row , col , SOUTH ) && ( dir != NORTH ))13
{14
getOut ( mzptr , row + 1, col , SOUTH , mode );15
}16
i f ( canMove ( mzptr , row , col , WEST ) && ( dir != EAST ))17
{18
getOut ( mzptr , row , col - 1, WEST , mode ) ;19
}20
i f ( canMove ( mzptr , row , col , NORTH ) && ( dir != SOUTH ))21
{22
getOut ( mzptr , row - 1, col , NORTH , mode );23
}24
// reachin g this point means the cell is a dead end25
// turn around and move backward26
(* mode ) = BACKWARD ;27
}28
In the forward mode, getOut calls itself and new frames are pushed onto the call stack.
In the backward mode, frames are popped from the call stack. This means returning to the