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

// 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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值