Children of the Candy Corn

本文探讨了迷宫求解算法的应用,通过DFS左、右遍历和BFS搜索算法解决迷宫问题,并实现了路径寻找到达终点的功能。

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

#include<stdio.h>
#include<string.h>
struct node
{
    int x;
    int y;
    int step;
}a[1600];
char maze[50][50];
int count,d;
int visit[40][40];
int fx[]= {0,1,0,-1};
int fy[]= {1,0,-1,0};
int fr[]= {1,0,3,2};
int fl[]= {3,0,1,2};
int dir[4][2]={1,0,-1,0,0,1,0,-1};
char sx,sy,ex,ey;
int w,h;
void dfsleft(int d,int x,int y)
{
    int tx,ty;
    if(x==ex&&y==ey)
    {
        printf("%d ",count);
        return ;
    }
    count++;
    for(int j=0;j<4;j++)
    {
        int i=(d+fl[j])%4;
        tx=x+fx[i];
        ty=y+fy[i];
        if(tx>=0&&tx<h&&ty>=0&&ty<w&&maze[tx][ty]!='#')
        {
            dfsleft(i,tx,ty);
            return;
        }
    }
}
void dfsright(int d,int x,int y)
{
    int tx,ty;
    if(x==ex&&y==ey)
    {
        printf("%d ",count);
        return ;
    }
    for(int j=0;j<4;j++)
    {
        int i=(d+fr[j])%4;
        tx=x+fx[i];
        ty=y+fy[i];
        if(tx>=0&&tx<h&&ty>=0&&ty<w&&maze[tx][ty]!='#')
        {
            count++;
            dfsright(i,tx,ty);
            return;
        }
    }
}
void bfs(int sx,int sy)
{ 
    a[0].x=sx;
    a[0].y=sy;
    a[0].step=0;
    int front=0;
    int rear=1;
    int tx,ty;
    memset(visit,0,sizeof(visit));
    visit[sx][sy]=1;
    while(front<rear)
    {
        node cur,exchange;
        cur=a[front++];
        if(cur.x==ex&&cur.y==ey)
        {
            printf("%d\n",cur.step+1);
        }
        for(int i=0;i<4;i++)
        {
            tx=cur.x+dir[i][0];
            ty=cur.y+dir[i][1];
            if(tx>=0&&tx<h&&ty>=0&&ty<w&&visit[tx][ty]==0&&maze[tx][ty]!='#')
            {
                visit[tx][ty]=1;
                exchange.x=tx;
                exchange.y=ty;
                exchange.step=cur.step+1;
                a[rear++]=exchange;
            }
        }
    }
}
int main()
{
    int cases=0;
    scanf("%d",&cases);
    while(cases--)
    {
        scanf("%d%d",&w,&h);
        for(int i=0;i<h;i++)
        {

            scanf("%s",maze[i]);
            for(int j=0;j<w;j++)
            {
                if(maze[i][j]=='S')
                {
                    sx=i;
                    sy=j;
                }
                if(maze[i][j]=='E')
                {
                    ex=i;
                    ey=j;
                }
            }
        }
        if(sx==0)d=0;
        if(sx==h-1)d=2;
        if(sy==0)d=1;
        if(sy==w-1)d=3;
        count=1;
        dfsleft(d,sx,sy);
        count=1;
        dfsright(d,sx,sy);
        bfs(sx,sy);
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值