迷宫DFS

DFS(非递归)

第一次写出一个迷宫。

其实也不难,虽热以前一直不会,知道有什么条件就可以了

比如迷宫用二维数组表示,有起点和终点,路,和障碍物四种元素

从起点出发,依次搜索四个方向,加判断条件。

遇到终点结束。其它情况要走向下一个格子需要注意一些条件。

1.是不是障碍物

2.该处是否被访问过

3.越界问题(因为走向下一个格子的表示是用坐标的x或y加1或者减1,所以要判断有没有越界)

如果没问题则走向下一个格子

然后修改相应的变量,再进行相应的操作

如果符合某一个条件则该方向不能通行,继续搜寻其它方向,如果其它方向都不能通行,

则反回上一个格子,从该格子开始继续搜寻其它的方向(这里比较难理解我觉得,

因为DFS是如果一个方向走得通就一直往那个方向走,一旦不通,返回的那个格子就还有别的方向没有搜,所以返回后继续搜索其它方向

),这样就可以找到终点了,至于要返回这条路径,应该可以有不同的方法,我用了栈的存储结构保存路径。

#include <bits/stdc++.h>

/* run this program using the console pauser or add your own getch, system("pause") or input loop */
using namespace std;

//坐标
typedef struct{
int x;
int y;
}position;

stack<position> dfs(int map[5][4],int tag[5][4],position start,position end){
position curpos=start;
curpos.x=start.x;
curpos.y=start.y;
stack<position> s;
s.push(start);
while(true){
if(curpos.x==2 && curpos.y==3){
break;
}
if(tag[curpos.x][curpos.y+1]==0 && map[curpos.x][curpos.y+1]!=1 && (curpos.y+1)<4 ){
curpos.y+=1;
s.push(curpos);
tag[curpos.x][curpos.y]=1;
}else if(tag[curpos.x][curpos.y-1]==0 && 1!=map[curpos.x][curpos.y-1] && (curpos.y-1)>=0){
curpos.y-=1;
s.push(curpos);
tag[curpos.x][curpos.y]=1;

}else if(tag[curpos.x+1][curpos.y]==0 && 1!=map[curpos.x+1][curpos.y] && (curpos.x+1)<5){
curpos.x+=1;
s.push(curpos);
tag[curpos.x][curpos.y]=1;

}else if(tag[curpos.x-1][curpos.y]==0 && 1!=map[curpos.x-1][curpos.y] && (curpos.x-1)>=0){
curpos.x-=1;
s.push(curpos);
tag[curpos.x][curpos.y]=1;

}else{
s.pop();
curpos=s.top();
}
}
return s;
}


int main(int argc, char** argv) {
int exitforstarandend=0;
int map[5][4]={
{666,0,0,1},
{1,0,1,1},
{0,0,1,999},
{0,1,0,0},
{0,0,0,1}
};
int tag[5][4]={{0,0,0,0},{0,0,0,0},{0,0,0,0},{0,0,0,0},{0,0,0,0}};
position start,end,pos;
//找到起点666和终点999
for(int i=0;i<5;i++){
for(int j=0;i<4;j++){
if(666==map[i][j]){
start.x=i;
start.y=j;
exitforstarandend++;
}
if(999==map[i][j]){
end.x=i;
end.y=j;
exitforstarandend++;
}
if(2==exitforstarandend){
break;
}
}
}
//获取路径栈(倒叙)
stack<position> s1=dfs(map,tag,start,end);
stack<position> s2;
position p1;
//正序
while(!s1.empty()){
p1=s1.top();
s2.push(p1);
s1.pop();
}
//打印路径(按坐标打印)
while(!s2.empty()){
p1=s2.top();
cout<<p1.x<<","<<p1.y<<endl;
s2.pop();
}
return 0;
}

猜你喜欢

转载自www.cnblogs.com/hyf001/p/11994841.html