您的位置:首页 > 其它

榆木脑壳练算法之迷宫寻路问题

2013-04-17 23:48 169 查看
// MazeProblem.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <process.h>

int maze[7][7] = {
{1, 1, 1, 1, 1, 1, 1},
{1, 0, 0, 0, 0, 0, 1},
{1, 1, 1, 0, 1, 1, 1},
{1, 0, 1, 1, 1, 1, 1},
{1, 1, 0, 0, 1, 1, 1},
{1, 0, 0, 0, 0, 0, 1},
{1, 1, 1, 1, 1, 1, 1}
};

int success = 0;
void findExit(int xPos, int yPos, const int mazeScope)
{
//2表示在xPos和yPos这一点已经走过的标记
maze[xPos][yPos] = 2;

//正常参数下递归的出口
if(xPos == (mazeScope - 2) && yPos == (mazeScope - 2))
{
if(maze[xPos][yPos] == 0)
{
success = 1;
}
}
else
{
//走路的试探方向分别是先向右,再向下,再向左,再向上
if(maze[xPos + 1][yPos] == 0 && success != 1)findExit(xPos + 1, yPos, mazeScope);
if(maze[xPos][yPos + 1] == 0 && success != 1)findExit(xPos, yPos + 1, mazeScope);
if(maze[xPos - 1][yPos] == 0 && success != 1)findExit(xPos - 1, yPos, mazeScope);
if(maze[xPos][yPos - 1] == 0 && success != 1)findExit(xPos, yPos - 1, mazeScope);
}

if(success == 1){
return;
}
else
{
//运行到这里的话,已经开始回溯,因为maze[xPos][yPos] = 2这一句,使得本来为0的通路
//不会再重新被递归到,此处也说明了该点不是一个出口路径上的点,需要恢复原样
maze[xPos][yPos] = 0;
}
}

void printIsHaveExit()
{
if(success == 1)
{
printf("There is a exit at in the maze");
}
else
{
printf("There is not a exit at in the maze");
}
}

/************************************************************************/
/* 假设有这样一个迷宫用0代表路,用1代表墙,做上角为入口,右下角为出口,
**求解迷宫中是否有这样的一条通路
*/
/************************************************************************/
int _tmain(int argc, _TCHAR* argv[])
{
findExit(1, 1, 7);
printIsHaveExit();

system("pause");
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: