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

来源:互联网 发布:淘宝用什么修图软件 编辑:程序博客网 时间:2024/05/22 08:05
// 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;}