#include <iostream>
using namespace std;
bool flag=false;
bool recursive(int x, int y,int s[12][12]); //递归走迷宫
int main()
{
bool result=false;
int count1=0; //统计路径长度
int M[12][12] = {
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, //起始点为(1,1)
1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1,
1, 0, 1, 0, 1, 1, 0, 0, 1, 0, 0, 1,
1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1,
1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1,
1, 1, 1, 1, 0, 1, 0, 1, 0, 0, 0, 1,
1, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 1,
1, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 1,
1, 0, 1, 1, 0, 1, 0, 1, 0, 0, 0, 1,
1, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 1, //终止点为(10,10)
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1
};
//打印起始迷宫图
cout << "The Enter is at (1,1):\n";
for (int i = 0; i < 12; i++)
{
if (i == 1)
{
cout << "Enter-->";
}
else
{
cout << " ";
}
for (int j = 0; j < 12; j++)
{
if (j == 11)
{
cout << M[i][j];
}
else
{
cout << M[i][j] << " ";
}
}
if (i == 10){ cout << "-->Exit"; }
cout << endl;
}
M[1][1] = 3; //起始时候将M[1][1]置为在路径中
result=recursive(1, 1, M); //开始查找路径
if (!result)
{
cout << "No Path!\n"; //不存在这样的路径
}
else
{
cout << "Path: "; //打印路径
for (int a = 0; a <12; a++)
{
if (a >= 1)
{
cout << " ";
}
for (int b = 0; b <12; b++)
{
if (M[a][b] == 3)
{
count1++;
cout << "maze[" << a << "][" << b << "],";
}
}
cout << endl;
}
cout << "Path Length: " << count1 << endl; //打印路径长度
cout << "One Path: \n"; //打印路径
//打印带路径的迷宫图
for (int i = 0; i < 12; i++)
{
if (i == 1)
{
cout << "Enter-->";
}
else
{
cout << " ";
}
for (int j = 0; j < 12; j++)
{
if (M[i][j] == 0 || M[i][j] == 1)
{
if (i == 10 && j == 11)
{
cout << M[i][j];
}
else
{
cout << M[i][j] << " ";
}
}
else if (M[i][j] == 2)
{
cout << "0" << " ";
}
else if (M[i][j] == 3)
{
cout << "x" << " ";
}
}
if (i == 10){ cout << "-->Exit"; }
cout << endl;
}
}
return 0;
}
//judge kernel
bool recursive(int x, int y, int s[12][12])
{
if (x == 10 && y == 10) //是否已已经完成路径搜索?
{
s[10][10] = 3;
return true;
}
if (s[1][1]==2){ return false; } //回退至起点?
if (s[x][y+1] == 0)
{
s[x][y + 1] = 3;
flag=recursive( x , y + 1, s); //向右移动
if (flag == true)
{
return true;
}
}
if (s[x + 1][y] == 0)
{
s[x + 1][y] = 3;
flag = recursive(x + 1, y, s); //向下移动
if (flag == true)
{
return true;
}
}
if (s[x - 1][y] == 0)
{
s[x - 1][y] = 3;
flag = recursive(x - 1, y, s); //向上移动
if (flag == true)
{
return true;
}
}
if (s[x - 1][y + 1] == 0)
{
s[x - 1][y + 1] = 3;
flag = recursive(x - 1, y + 1, s); //向右上角移动
if (flag == true)
{
return true;
}
}
if (s[x + 1][y + 1] == 0)
{
s[x + 1][y + 1] = 3;
flag = recursive(x + 1, y + 1, s); //向右下角移动
if (flag == true)
{
return true;
}
}
if (s[x + 1][y - 1] == 0)
{
s[x + 1][y - 1] = 3;
flag = recursive(x + 1, y - 1, s); //向左下角移动
if (flag == true)
{
return true;
}
}
if (s[x][y - 1] == 0)
{
s[x][y - 1] = 3;
flag = recursive(x, y - 1, s); //向左移动
if (flag == true)
{
return true;
}
}
if (s[x - 1][y - 1] == 0)
{
s[x - 1][y - 1] = 3;
flag = recursive(x - 1, y - 1, s); //向左上角移动
if (flag == true)
{
return true;
}
}
s[x][y] = 2; //标记当前需回退的元素
return flag; //返回最前节点的寻路信息
}