Finding the Exit of a Maze 379
canMove ( mzptr , row , col , SOUTH ) &&26
( dir != NORTH ))27
{28
(* mode ) = FORWARD ;29
getOut ( mzptr , row + 1, col , SOUTH , mode );30
i f ((* mode ) == BAC K W ARD )31
{32
printf (" Move to (% d ,% d) n" , row , col ) ;33
}34
}35
i f (((* mode ) != DONE ) &&36
canMove ( mzptr , row , col , WEST ) &&37
( dir != EAST ) )38
{39
(* mode ) = FORWARD ;40
getOut ( mzptr , row , col - 1, WEST , mode ) ;41
i f ((* mode ) == BAC K W ARD )42
{43
printf (" Move to (% d ,% d) n" , row , col ) ;44
}45
}46
i f (((* mode ) != DONE ) &&47
canMove ( mzptr , row , col , NORTH ) &&48
( dir != SOUTH ))49
{50
(* mode ) = FORWARD ;51
getOut ( mzptr , row - 1, col , NORTH , mode );52
i f ((* mode ) == BAC K W ARD )53
{54
printf (" Move to (% d ,% d) n" , row , col ) ;55
}56
}57
i f ((* mode ) != DONE )58
{59
(* mode ) = BACKWARD ;60
}61
}62
This is the final version of the getOut function. This final version getOut solves the
maze. It can be driven by the main function as shown below:
#in clude < stdio .h >1
#in clude " maze . h"2
void getOut ( Maze * mzptr , i n t row , in t col ,3
int dir , int * mode );4
int main ( i n t argc , char * argv [])5
{6
i f ( argc < 2)7
{8
fprintf ( stderr , " need a file name n" );9
return -1;10
}11
380 Intermediate C Programming
Maze * mzptr = Maze_ constr u ct ( argv [1]) ;12
i f ( mzptr == 0) { return -1; }13
/* Maz e_print ( mzptr ); */14
int progress = FORWARD ;15
getOut ( mzptr , mzptr -> startRow , mzptr -> startCol ,16
ORIGIN , & pro g ress );17
Maze_ destruc t ( mzptr ) ;18
return 0;19
}20
This program shows how to use structures and recursion together. By using recursion,
the visited locations are stored in the call stack as function arguments. This allows the
program to backtrack after visiting dead ends.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset