用简单递归方法解决老鼠走迷宫问题
在复习递归算法的时候,脑袋里突然浮现出老鼠走迷宫问题,既然想到了,那么接下来就让我们用C++实现它吧,自己争取用易于理解和阅读的方式实现。
1、问题说明:
老鼠走迷宫是递归求解的基本题型,我们在二维阵列中使用2表示迷宫墙壁,使用1来表示老鼠的行走路径,试以程序求出由入口至出口的路径
2、解法:
老鼠的走法有上、下、左、右四个方向,在每前进一格之后就选一个方向前进,无法前进时退回选择下一个可前进方向,如此在阵列中依序测试四个方向,知道走到出口为止。
3、具体代码:
/**
* @Title 老鼠走迷宫
* @Author 孙琨
* @Date 2013-11-16
* @At XUST
* @All Copyright by 孙琨
*
*/
#include <iostream>
using namespace std;
int maze[7][7] = { // 初始化迷宫,英文maze为“迷宫”
{2,2,2,2,2,2,2},
{2,0,0,0,0,0,2},
{2,0,2,0,2,0,2},
{2,0,0,2,0,2,2},
{2,2,0,2,0,2,2},
{2,0,0,0,0,0,2},
{2,2,2,2,2,2,2}
};
int startI = 1,startJ = 1; // 入口行列坐标
int endI = 5,endJ = 5; // 出口行列坐标
int success = 0; // 判断路是否走通
int visit(int i,int j) // 自动搜寻路径
{
maze[i][j] = 1;
if((i == endI) && (j == endJ))
success = 1;
if((success != 1) && (maze[i][j+1] == 0)) // 下
visit(i,j+1);
if((success != 1) && (maze[i+1][j]) == 0) // 右
visit(i+1,j);
if((success != 1) && (maze[i][j-1] == 0)) // 上
visit(i,j-1);
if((success != 1) && (maze[i-1][j] == 0)) // 左
visit(i-1,j);
if(success != 1)
maze[i][j] = 0;
return success;
}
int main(void)
{
int i,j;
cout << "显示迷宫: " << endl;
for(i=0; i<7; i++)
{
for(j=0; j<7; j++)
{
if(maze[i][j] == 2)
cout << "■" ;
else
cout << " " ;
}
cout << endl;
}
if(visit(startI,startJ) == 0)
{
cout << endl << "没有找到出口!" << endl;
}
else
{
cout << endl << "显示路径: " << endl;
for(i=0; i<7; i++)
{
for(j=0; j<7; j++)
{
if(maze[i][j] == 2)
cout << "■";
else if(maze[i][j] == 1)
cout << "♀";
else
cout << " ";
}
cout << endl;
}
}
return 0;
}
4、运行结果截图