迷宫问题 poj 3984 搜索算法 宽搜+dfs回溯

本文介绍了一种基于广度优先搜索(BFS)的迷宫寻路算法,并通过回溯深度优先搜索(DFS)来展示寻路路径。文中提供了一个具体的迷宫示例和完整的C++代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目链接地址

很简单的搜索,只要广搜就可以了,然后就是记录搜索地址,最后我竟然又用了一遍DFS(),求出了最后的路径。

0 1 0 0 0
0 1 0 1 0
0 0 0 0 0
0 1 1 1 0
0 0 0 1 0

宽搜后的结果,然后再DFS回溯求返回路径就可以

1 0 7 8 0
2 0 6 0 8
3 4 5 6 7
4 0 0 0 8
5 6 7 0 9

最近第一次写搜索~~勿喷:

#include<stdio.h>
#include<string.h>
#include<queue>
#include<stack>
#include<iostream>
using namespace std;
struct node{
       int x,y,step;
       node(){}
       node(int a,int b,int c):x(a),y(b),step(c){}
}tmp;
int dx[6]={0,0,0,1,-1};
int dy[6]={0,1,-1,0,0};
int point[7][7];
int rec[7][7];
queue <struct node> que;
void dfs(node t){           //回溯算法
    for(int i=1;i<=4;i++){
         int x=t.x+dx[i],y=t.y+dy[i];
         if(x<1||x>5||y<1||y>5)continue;
         if(rec[x][y]==t.step-1&&rec[x][y]>=1){
             dfs( node(x,y,rec[x][y]) );
             printf("(%d, %d)\n",x-1,y-1);
         }

    }
}
int main()
{
     while(scanf("%d",&point[1][1])!=EOF){
           int step=1;
           memset(point,0,sizeof(point));
           memset(rec,0,sizeof(rec));
           for(int i=2;i<=5;i++)
             scanf("%d",&point[1][i]);
           for(int i=2;i<=5;i++)
              for(int j=1;j<=5;j++)
                 scanf("%d",&point[i][j]);
           while(que.empty()!=true)que.pop();  //将队列元素全部清除
           rec[1][1]=step;
           que.push(node(1,1,1));
           while(que.empty()!=true){                //宽搜
                tmp=que.front();
                que.pop();
                for(int i=1;i<=4;i++){                  
                   int x=tmp.x+dx[i],y=tmp.y+dy[i];
                   if(point[x][y]==1)continue;      //不能撞墙
                   if(x<1||x>5||y<1||y>5)continue;  //界限判定
                   if(rec[x][y]!=0)continue;        //是否经过
                   rec[x][y]=tmp.step+1;
                   if(x==5&&y==5)goto end;
                   //cout<<x<<" "<<y<<" "<<rec[x][y]<<endl;
                   que.push(node(x,y,rec[x][y]) );
                }
           }
           end:;
           dfs(node(5,5,rec[5][5]));
           printf("(%d, %d)\n",4,4);

     }

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值