1240:Asteroids!

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1240

方法:bfs

思路:和一般的地图搜索相似,但是这个涉及到了三维空间,因此走的方向也就拓展到了六个。如果比较熟悉bfs的话,那么本题写出bfs应该不算难,主要是这六个方向的表示问题,可以把这六个方向储存为一个6行3列的数组,调用时只需要不断遍历这个数组就可以了。还要注意,一般bfs地图题都会涉及到多个变量,因此开一个结构体是必须的,另外地图题的判定条件非常繁琐的话,可以单独写一个函数便于调用。

难点:题目说有100个数据,我就这么干了,WA了,然后改为直接读到文件尾,AC了.......

#include<iostream>
#include<string>
#include<queue>
#include<cstring>
using namespace std;
const int MAX = 15;
int sx,sy,sz,ex,ey,ez;
int ans = -1;
int num;
bool mark[MAX][MAX][MAX];
char maze[MAX][MAX][MAX];
int dir[6][3] ={{1,0,0},{0,1,0},{0,0,1},{-1,0,0},{0,-1,0},{0,0,-1}};
struct node
{
    int x,y,z,step;
};
bool check(node p)
{
    if(p.x >= num || p.x < 0 || p.y >= num || p.y < 0 || p.z >= num || p.z < 0)
        return 1;
    if(mark[p.x][p.y][p.z] == 1)
        return 1;
    if(maze[p.x][p.y][p.z] == 'X')
        return 1;
    return 0;
}
void bfs()
{
    memset(mark,0,sizeof(mark));
    ans = -1;
    queue<node> Q;
    node p,t,next;
    p.x = sx;
    p.y = sy;
    p.z = sz;
    p.step = 0;
    Q.push(p);
    while(!Q.empty())
    {
        t = Q.front();
        Q.pop();
        if(t.x == ez && t.y == ey && t.z == ex)
        {
            //cout<<"a"<<endl;
            ans = t.step;
            return;
        }
        for(int i = 0;i < 6;i++)
        {
                next.x = t.x+dir[i][0];
                next.y = t.y+dir[i][1];
                next.z = t.z+dir[i][2];
                next.step = t.step+1;
                if(!check(next))
                {
                    Q.push(next);
                    mark[next.x][next.y][next.z] = 1;
                }
        }
    }
    return ;
}
int main()
{
    string s;
    while(cin>>s)
    {
        //cout<<s<<endl;
        cin>>num;
        //cout<<num<<endl;
        for(int i = 0;i < num;i++)
        {
            for(int j = 0;j < num;j++)
            {
                for(int k = 0;k < num;k++)
                    cin>>maze[i][j][k];
            }
        }
        cin>>sx>>sy>>sz;
        //cout<<sx<<sy<<sz<<endl;
        cin>>ex>>ey>>ez;
        //cout<<ex<<ey<<ez<<endl;
        cin>>s;
        //cout<<s<<endl;
        bfs();
        if(ans == -1)
            cout<<"NO ROUTE"<<endl;
        else
            cout<<num<<" "<<ans<<endl;
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值