HDU 1240 Asteroids!

三维广搜

#include <cstdio>
#include <iostream>
#include <cstring>
#include <queue>
using namespace std;
 
struct node
{
    int x,y,z;
    int steps;
}start,end,next;
int dx[6]={0,0,0,0,1,-1};    
int dy[6]={0,0,-1,1,0,0};
int dz[6]={1,-1,0,0,0,0};
char maps[15][15][15];
int n,res;
 
bool check(node &a)
{
    if(a.x>=0&&a.x<n&&a.y>=0&&a.y<n&&a.z>=0&&a.z<n)
        return true;
    else return false;
}
 
int bfs()
{
    if(start.x==end.x&&start.y==end.y&&start.z==end.z)
        return res;
    node cur;
    queue<node> q;
    while(!q.empty())
        q.pop();
    q.push(start);
    maps[start.x][start.y][start.z]='X';
    while(!q.empty())
    {
        cur=q.front();
        q.pop();
        for(int i=0;i<6;i++)
        {
            next.x=cur.x+dx[i];
            next.y=cur.y+dy[i];
            next.z=cur.z+dz[i];
            if(next.x==end.x&&next.y==end.y&&next.z==end.z) 
                return cur.steps+1;                             
            if(maps[next.x][next.y][next.z]=='O'&&check(next))
            {
                next.steps=cur.steps+1;
                maps[next.x][next.y][next.z]='X';
                q.push(next);
            }
        }
    }
    return -1;
}
 
int main()
{
    int i,j;
    char st[6],ed[6];
    while(scanf("%s%d",&st,&n)!=EOF)
    {
        getchar();
        for(i=0;i<n;i++)
        {
            for(j=0;j<n;j++)
                scanf("%s",maps[i][j]);
            getchar();
        }
        scanf("%d%d%d",&start.x,&start.y,&start.z);
        scanf("%d%d%d",&end.x,&end.y,&end.z);
        getchar();
        gets(ed);
        res=0;
        start.steps=0;
        res=bfs();
        if(res>=0) printf("%d %d
",n,res);
        else printf("NO ROUTE
");
    }
    return 0;
}
原文地址:https://www.cnblogs.com/forever97/p/3541218.html