原题:
You're in space.
You want to get home.
There are asteroids.
You don't want to hit them.
题意:
你在太空中,用三维矩阵给出你可以走的路线,和你开始位置和要去的位置。
题解:
用广搜,因为只需要求出需要的步数,所以先搜索到的位置肯定需要的步数要小与等于以后的步数,然后定义结构体,包括这个点的三维坐标和走过来的步数,然后广搜函数也不是很难写。难的是!三维数组的输入!搞蒙了......之前没怎么用过,输入顺序搞反了,后来查了查改过来了。
代码:AC
#include<iostream>
#include<queue>
#include<cstdio>
#include<cstring>
using namespace std;
char space[20][20][20];
int visit[20][20][20];
int fx[]={1,-1,0,0,0,0};
int fy[]={0,0,1,-1,0,0};
int fz[]={0,0,0,0,1,-1};
int n;
int sx,sy,sz,ex,ey,ez;
typedef struct
{
int x,y,z;
int step;
}node;
int check(int x,int y,int z)
{
if(x>=0&&y>=0&&z>=0&&x<n&&y<n&&z<n&&visit[x][y][z]==0&&space[x][y][z]=='O')
return 1;
return 0;
}
int BFS(int x,int y,int z)
{
queue<node>Q;
node a, next;
a.x=x;
a.y=y;
a.z=z;
a.step=0;
visit[x][y][z]=1;
Q.push(a);
while(!Q.empty())
{
a=Q.front();
Q.pop();
if(a.x==ex&&a.y==ey&&a.z==ez)
return a.step;
int i;
for(i=0;i<6;i++)
{
next=a;
next.x+=fx[i];
next.y+=fy[i];
next.z+=fz[i];
if(check(next.x,next.y,next.z))
{
next.step++;
visit[next.x][next.y][next.z]=1;
Q.push(next);
}
}
}
return -1;
}
int main()
{
char start[20];
while(cin>>start>>n)
{
int i,j,k;
for(i=0;i<n;i++)
for(j=0;j<n;j++)
for(k=0;k<n;k++)
cin>>space[k][j][i];
cin>>sx>>sy>>sz>>ex>>ey>>ez;
cin>>start;
int ans=BFS(sx,sy,sz);
if(ans>=0)
cout<<n<<" "<<ans<<endl;
else
cout<<"NO ROUTE"<<endl;
memset(visit,0,sizeof(visit));
}
return 0;
}