c++迷宫问题(递归)输出异常 3C

#include
using namespace std;
int R1[40] ;//储存结果用于输出
int R2[40] ;
int c = 0;
int cou = 0;
int Maze[9][9] = {
0,0,0,0,0,0,1,1,0,
1,0,1,1,0,0,1,1,0,
0,0,1,0,1,0,1,1,0,
0,1,1,1,0,0,1,1,0,
0,1,0,1,0,0,1,0,0,
0,1,0,1,0,0,0,0,0,
0,1,0,0,1,0,1,0,0,
0,1,0,0,1,1,0,0,0,
0,1,0,0,1,1,1,0,0
};//初始化迷宫
int visited[9][9];//访问权限 0为未访问
//走迷宫
void DFS(int m, int n)
{
if (m >= 0 && n >= 0 && m <= 8 && n <= 8) {//限制有效数据范围
if (visited[m][n] == 0 && Maze[m][n] == 0)//判断条件:1.该单元格未访问过 2.该单元格是通路
{

``````            R1[c] = m + 1;//存入结果
R2[c] = n + 1;
c++;//R数组下标:记录长度
visited[m][n] = 1;
if (visited[8][8] == 1) {
//输出结果
for (int i = 0; i < 40; i++)
if (R1[i] != -1 && R1[i] != 0 && R2[i] != -1 && R2[i] != 0)
cout << "(" << R1[i] << "," << R2[i] << ") ";
cout << endl;
c--;
R1[c] = 0;
R2[c] = 0;
visited[m][n] = 0;
return;
}
DFS(m, n + 1);//向右查找
DFS(m + 1, n);//向下查找
DFS(m - 1, n);//向上查找
DFS(m, n - 1);//向左查找
//执行结束进行退出操作
c--;
R1[c] = 0;
R2[c] = 0;
visited[m][n] = 0;
}
}
``````

}
void main()
{
cout << "迷宫走法如下:" << endl;
DFS(0, 0);//入口(1,1)
}

1个回答