poj 3083 Children of the Candy Corn

本文分享了一位参赛者在NOIP竞赛准备过程中对于搜索算法的理解与实践。通过具体题目,详细介绍了如何利用DFS实现迷宫寻路,并采用BFS进行路径优化。文章还包含了完整的C++代码实现。

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

唔。为什么我最近开始写搜索列表了?
因为暴力太差了,
致使考试深受打击。
你说想正解?对对对这个也要练。
但是代码能力真的是差到爆炸。。还有28天noip。搜索预计只在给4天的时间。不能再多了。
注意ac率。。。。。。。。
所以说着题目:
主要就是要记个方向处理一下方向的顺序就ok了。
不用写2个dfs,只要把起点和重点交换一下就ok了。
dfs不要记vis。。因为可以重复的为什么不会炸?只要搜索的路径方向是正确的就不会。。

#include<cstdio>
#include<queue>
#include<cstring>
#include<algorithm>
using namespace std;
//by mars_ch
//0 up   1 r   2 d   3 l
int t,n,m; 
struct data
{
    int x,y,step;
}s,e,p;
int sx,sy,ex,ey;
char map[45][45];
int now,ansl,ansr,ans,res;
int vis[45][45];
int dx[5]={-1,0,1,0};
int dy[5]={0,1,0,-1};
bool flag;
queue<data> q;
void dfs(int x,int y,int step)
{
    for(int i=1;i<=4;i++)
    {
        if(flag) return;
        if(i == 1) now+=3;
        else now++; 
        if(now>4) now%=4;
        int nx=x+dx[now-1];
        int ny=y+dy[now-1];
        //puts("");puts("");puts("");
        //printf("%d %d\n",nx,ny);
        if(nx<=0 || ny<=0 || nx>n || ny>m) continue;
        if(map[nx][ny] == '#') continue;

        //printf("%d %d\n",nx,ny);
        if(nx == ex && ny == ey)
        {
            flag=true;
            res=step+1;
            return;
        }
        dfs(nx,ny,step+1);
    }
}
void bfs()
{
    while(!q.empty())
    {
        q.pop();
    }
    q.push(s);
    vis[s.x][s.y]=1;
    while(!q.empty())
    {
        data u=q.front();
        q.pop();

        for(int i=0;i<4;i++)
        {
            int nx=u.x+dx[i],ny=u.y+dy[i];
            if(vis[nx][ny]) continue;
            if(nx<=0 || ny<=0 || nx>n || ny>m) continue;
            if(map[nx][ny] == '#') continue;

            vis[nx][ny]=1;
            data t;
            t.x=nx,t.y=ny,t.step=u.step+1;
            if(nx == e.x && ny == e.y)
            {
                ans=t.step;
                return;
            }
            q.push(t);
        }
    }
}
int main()
{
    scanf("%d",&t);
    while(t--)
    {
        scanf("%d%d",&m,&n);
        scanf("\n");
        for(int i=1;i<=n;i++)
        {
            for(int j=1;j<=m;j++)
            {
                scanf("%c",&map[i][j]);
                if(map[i][j] == 'S') sx=i,sy=j;
                if(map[i][j] == 'E') ex=i,ey=j;
            }
            scanf("\n"); 
        }
        s.x=sx,s.y=sy,s.step=1;
        e.x=ex,e.y=ey;
        now=1;
        flag=false;
        dfs(sx,sy,1);
        ansl=res;

        now=1,res=0;
        flag=false;
        swap(sx,ex),swap(sy,ey);
        dfs(sx,sy,1);
        ansr=res;

        memset(vis,0,sizeof(vis));
        bfs();

        printf("%d %d %d\n",ansl,ansr,ans);
    }

    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值