老鼠走迷宫是一个典型的递归的问题,写几个这样的题才可以充分理解递归的过程。
写递归的过程有几点需要注意:
(1)递归结束的条件
(2)递归过程的脉络,即逻辑要清晰。
/
//
// 在迷宫中显示老鼠能走出的迷宫的一条路径
//
//
/
#include
#include
#define Wide 8
#define Height 8
// 迷宫设计
int maze[8][8] = {
{ 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 } ,
{ 1 , 0 , 0 , 0 , 1 , 1 , 1 , 1 } ,
{ 1 , 0 , 0 , 0 , 0 , 1 , 1 , 1 } ,
{ 1 , 1 , 0 , 0 , 0 , 0 , 0 , 1 } ,
{ 1 , 0 , 0 , 1 , 0 , 1 , 0 , 1 } ,
{ 1 , 0 , 0 , 1 , 1 , 0 , 0 , 1 } ,
{ 1 , 0 , 0 , 0 , 0 , 0 , 0 , 1 } ,
{ 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 } } ;
int startX = 1 ; // 开始处
int startY = 1 ;
int endX = 6 ; // 结束处
int endY = 6 ;
bool success = false ;
// 显示迷宫
void showMaze()
{
for( int i = 0 ; i < Wide ; i++ )
{
for( int j = 0 ; j < Height ; j++ )
{
if( maze[i][j] == 1 )
{
printf("□") ;
}
else
{
printf(" ") ;
}
}
printf("\n") ;
}
}
// 显示结果
void showResult()
{
for( int i = 0 ; i < Wide ; i++ )
{
for( int j = 0 ; j < Height ; j++ )
{
if( maze[i][j] == 1 )
{
printf("□") ;
}
else if( maze[i][j] == 2 )
{
printf("☆") ;
}
else
{
printf(" ") ;
}
}
printf("\n") ;
}
}
int visit( int x , int y )
{
maze[x][y] = 2 ; // 标记为路径中的一点
if( x == endX && y == endY ) // 判断是否到达终点
{
success = true ; // 找到终点
return 1 ;
}
// 向上
if( maze[x-1][y] == 0 )
{
if( visit( x-1 , y ) == 1 )
{
return 1 ;
}
}
// 向下
if( maze[x+1][y] == 0 )
{
if( visit( x+1 , y) == 1 )
{
return 1 ;
}
}
// 向左
if( maze[x][y-1] == 0 )
{
if( visit( x , y - 1 ) == 1 )
{
return 1 ;
}
}
// 向右
if( maze[x][y+1] == 0 )
{
if( visit( x , y + 1 ) == 1 )
{
return 1 ;
}
}
maze[x][y] = 0 ; // 说明此位置无法到达终点,在路径中去掉该点
return -1 ;
}
int main()
{
int x = startX ;
int y = startY ;
showMaze() ;
printf("\n\n") ;
visit( x , y ) ;
if( success == false )
{
printf("找不到终点!\n") ;
}
else
{
printf("找到终点!\n") ;
showResult() ;
}
return 0 ;
}