Ss 老鼠走迷宫问题(只求一条路)(老规矩:读者自己先根据提示写,最后看答案please)
1. 标志变量(递归总开关,减少递归次数)succ(默认为false),如果找到了最终路径则将succ设为true,否则设为false,每一个递归体的条件都与上(!succ),这样如果找到的话就不用再递归了,递归终止条件是succ==true
2. 三种状态:墙壁设为2,通路设为0,已经走过的通路设为1(每次递归开始之前设),每一层递归结束的时候如果succ为false的话,将当前通路点重新设为0(该步是为了以后正确打印迷宫);
3. return succ(为了第一层递归正确返回值)
4. 也可以结合全局栈来存储路径
/*2 is the wall,0 is the path*/
#include<iostream>
#include<stdio.h>
#include<fstream>
using namespace std;
int maze[500][500];
int m[250000],ptr=-1;
pair<int,int> stack[500];
int succ = 0;
bool visit(int x, int y, int xaim, int yaim){
maze[x][y] = 1;
stack[++ptr].first = x;
stack[ptr].second = y;
if (x == xaim&&y == yaim)succ = 1;
if (succ != 1 && maze[x + 1][y] == 0) visit(x + 1, y, xaim, yaim);
if (succ != 1 && maze[x][y - 1] == 0) visit(x, y - 1, xaim, yaim);
if (succ != 1 && maze[x - 1][y] == 0)visit(x - 1, y, xaim, yaim);
if (succ != 1 && maze[x][y + 1] == 0)visit(x, y + 1, xaim, yaim);
if (succ != 1) { maze[x][y] = 0; ptr--; }
return succ;
}
void print(){
cout << "x" << "\t" << "y" << endl;
int i = 0;
while (i<=ptr){
cout << stack[i].first << "\t" << stack[i].second << "\t" << endl;
i++;
}
}
int main(int argv,char**argc){
ifstream in("input.txt");
int cnt = 0;
for (; in >> m[cnt];cnt++);//i is the scale of the number
int dim = 2;
while (dim*dim != cnt)dim++; //compute the dimension
for (int row = 0,num=0; row != dim;row++)
for (int col = 0; col != dim; col++)
maze[row][col] = m[num++]; //compute the maze;
bool judge = visit(1,1,7,7);
if (judge == true) print();
else cout << "can not find a path" << endl;
system("pause");
return 0;
}