POJ 2251(基础三维BFS)

poj2251

题目大意

在一个三维格子里面, 有两种格子,一种可以走一种不能。给定一个起点和终点问从起点最少走多少步可以到达终点。

分析

很基础的一道bfs,在这里记录一下以后处理类似的问题一个技巧:通过xx[]、yy[]、zz[]数组实现一个人循环将一个节点周围的元素入队。

代码

#include<cstdio>
#include<iostream>
#include<cmath>
#include<cstring>
#include<cstdlib>
#include<queue>
#include<stack>
using namespace std;
const int INF=999999999;
int cube[35][35][35];
bool bj[35][35][35];
int step[35][35][35];
int xx[6]={1,-1,0,0,0,0};
int yy[6]={0,0,0,0,1,-1};
int zz[6]={0,0,1,-1,0,0};
int L,R,C;
int ans;
struct Node
{
    int x;
    int y;
    int z;
    Node(){}
    Node(int i,int j,int k)
    {
          x=i;y=j;z=k;
    }
}S,E;
void Init()
{
      ans=0;
      memset(bj,0,sizeof(bj));
      memset(step,0,sizeof(step));
}
bool Is_out(int x,int y,int z)
{
      if(z>L || x>R || y>C)return 1;
      else return 0;
}
bool Is_End(int x,int y,int z)
{
      if(x==E.x && y==E.y && z==E.z)return 1;
      else return 0;
}
void bfs()
{
       queue<Node> Q;
       Q.push(S);
       int x,y,z;
       x=S.x;y=S.y;z=S.z;
       bj[x][y][z]=1;
       step[x][y][z]=0;
       while(!Q.empty())
       {
             Node t=Q.front();
             int tx,ty,tz;
             tx=t.x;
             ty=t.y;
             tz=t.z;
             if(Is_End(tx,ty,tz)){ans=step[tx][ty][tz];break;}
             Q.pop();
             for(int i=0;i<6;i++)
             {
                   if(!Is_out(tx+xx[i],ty+yy[i],tz+zz[i]) && cube[tx+xx[i]][ty+yy[i]][tz+zz[i]]==1 && bj[tx+xx[i]][ty+yy[i]][tz+zz[i]]==0)
                   {
                        Node temp(tx+xx[i],ty+yy[i],tz+zz[i]);
                        bj[tx+xx[i]][ty+yy[i]][tz+zz[i]]=1;
                        step[tx+xx[i]][ty+yy[i]][tz+zz[i]]=step[tx][ty][tz]+1;
                        Q.push(temp);
                   }
             }
       }

}
int main()
{
    char c;
    while(scanf("%d%d%d",&L,&R,&C)!=EOF)
    {
          Init();
          if(L==0 && R==0 && C==0)break;
          for(int z=1;z<=L;z++)
          {
                for(int x=1;x<=R;x++)
                {
                      for(int y=1;y<=C;y++)
                      {
                            scanf("%c",&c);
                            while(c==' ' || c=='\n')scanf("%c",&c);
                            if(c=='#')cube[x][y][z]=0;
                            else cube[x][y][z]=1;
                            if(c=='S'){S.x=x;S.y=y;S.z=z;}
                            if(c=='E'){E.x=x;E.y=y;E.z=z;}
                      }
                }
          }
          bfs();
          if(ans)printf("Escaped in %d minute(s).\n",ans);
          else printf("Trapped!\n");
    }
    return 0;
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值