hdu~1240(bfs)

这题是道三维bfs,我在坐标上坑了。

1.输入的x,y,z是从0开始的。

2.seat[z][y][x]:第一维存的才是z坐标,在这个地方坑了几个小时。。

3.判断到终点的语句要放在for外面,不然会漏掉起点等于终点的情况


<span style="font-size:18px;">#include <stdio.h>
#include <queue>
#define MAX 15
#define INF 0xffffff

char seat[MAX][MAX][MAX];
int a,b,c,t,ans,n;
int sx,sy,sz,ex,ey,ez;		//存起始位置
int dir[10][3]={0,0,0,1,0,0,0,1,0,-1,0,0,0,-1,0,0,0,1,0,0,-1};	//存6个方向

typedef struct ac
{
    int x,y,z,step;
}node;

using namespace std;

void bfs(int z,int y,int x,int step)
{
    queue <node > q;
    node next,temp;
    next.x=x;
    next.y=y;
    next.z=z;
    next.step=step;
    seat[z][y][x]='X';
    q.push(next);
    while(!q.empty())
    {
        next=q.front();
        q.pop();
   //     printf("sxyz:%d %d %d %d\n",x,y,z,step); 
        if(next.x==ex && next.y==ey && next.z==ez)<span style="white-space:pre">	</span>//特别注意,在for之外</span><span style="font-size: 18px; font-family: Arial, Helvetica, sans-serif;">判断是否到终点。</span><span style="font-size:18px;">
        {
        //    printf("!!%d %d %d %d\n",temp.x,temp.y,temp.z,temp.step);
            ans=next.step;
            return ;
        }
        for(int i=1;i<=6;i++)
        {
            temp.x=next.x+dir[i][0];
            temp.y=next.y+dir[i][1];
            temp.z=next.z+dir[i][2];
            temp.step=next.step+1;
            //printf("temp:%d %d %d %d\n",temp.x,temp.y,temp.z,temp.step);
            if(temp.x<1 || temp.x>n || temp.y<1 || temp.y>n || temp.z<1 || temp.z>n)//出界
                    continue;
            if(seat[temp.z][temp.y][temp.x]=='X')//撞陨石
                continue;
            //printf("%d %d %d %d\n",temp.x,temp.y,temp.z,temp.step);
           
            seat[temp.z][temp.y][temp.x]='X';//走过
            q.push(temp);
        }
    }
}
int main()
{
    char s[123];
    int i,j;
    while(scanf("%s %d",s,&n)!=EOF)
    {
        for(i=1;i<=n;i++)
            for(j=1;j<=n;j++)
                scanf("%s",&seat[i][j][1]);
        scanf("%d %d %d",&sx,&sy,&sz);
        scanf("%d %d %d",&ex,&ey,&ez);
        sx++,sy++,sz++,ex++,ey++,ez++; //因为我习惯从1开始,所以坐标++转换一下。
        scanf("%s",s);
        ans=INF;
            bfs(sz,sy,sx,0);//seat第一维存的是z坐标。
        if(ans==INF)
            printf("NO ROUTE\n");
        else
            printf("%d %d\n",n,ans);
    }
    return 0;
}</span>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值