上面之所以要强调非最短路径,是因为在下一篇我要用BFS来求解最短路径的问题。这里只是讲如何走出迷宫。
#include<cstdio>
#define M 10
#define N 10
using namespace std;
void mi(int x,int y);
int a[N][M] = {//从(0,1)到最下面的2位置,1围墙,0路径
1,1,1,1,1,1,1,1,0,1,
0,0,0,0,0,0,1,0,0,1,
0,1,0,1,1,0,1,1,0,1,
0,1,0,0,0,0,0,0,0,0,
1,1,0,1,1,0,1,1,1,1,
0,0,0,0,1,0,0,0,0,1,
0,1,1,1,1,1,1,1,0,1,
0,0,0,0,1,0,0,0,0,0,
0,1,1,1,1,0,1,1,1,0,
0,0,0,0,1,0,0,0,2,1
};
int v[N][M] = {0};
int count = 0;//记录步数
int main(){
for(int i = 0; i<M; i++){
for(int j = 0; j<N ; j++)
printf("%d\t",a[i][j]);
printf("\n");
}
mi(0,1);
printf("count :%d\t",count);
return 0;
}
void mi(int x,int y){
if(a[x][y] == 2)return;
if(a[x+1][y] == 0 && x+1 < M && v[x+1][y] == 0){//下
v[x+1][y] =1;
mi(x+1,y);
//printf(x+1,y);需要打印的话
count++;
}
if(a[x-1][y] == 0 && x-1>=0 && v[x-1][y] == 0){上
v[x-1][y] =1;
mi(x-1,y);
count++;
}
if(a[x][y-1] == 0 && y-1>=0 && v[x][y-1] == 0){//左
v[x][y-1] =1;
mi(x,y-1);
count++;
}
if(a[x][y+1] == 0 && y+1 < M && v[x][y+1] ==0){//右
v[x][y+1] =1;
mi(x,y+1);
count++;
}
}
结果如下: