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