#小白日记.1 HDU1240 Asteroids!
题目大意:三维空间的走迷宫。
注意题目中x,y,z坐标的定义。
比较常规的BFS题目
需要用到三维数组
下面是代码:
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <queue>
#include <iostream>
#include <string>
using namespace std;
char maze[11][11][11];//地图
int N,ax,ay,az,bx,by,bz,ok;
struct node{
int x,y,z;
int t; //第几步
};
int wlk[6][3]={{0,0,1},{0,0,-1},{0,1,0},{0,-1,0},{1,0,0},{-1,0,0}};//六个方向行走
int Judge(int x,int y,int z){//判断是否可以走
if(x>=0&&x<N&&y>=0&&y<N&&z>=0&&z<N&&maze[x][y][z]=='O')
return 1;
else return 0;
}
void Bfs()
{
ok=0;
node now,next;
queue <node> q;
now.x=ax;
now.y=ay;
now.z=az;
now.t=0;
maze[ax][ay][az]='X';
q.push(now);
while(!q.empty()){
now=q.front();
q.pop();
if(now.x==bx&&now.y==by&&now.z==bz){
ok=1;
cout<<N<<" "<<now.t<<endl;
break;
}
next.t++;
for(int i=0;i<6;i++){
next.x=now.x+wlk[i][0];
next.y=now.y+wlk[i][1];
next.z=now.z+wlk[i][2];
next.t=now.t+1;//
if(Judge(next.x,next.y,next.z)){
// cout<<next.x<<" "<<next.y<<" "<<next.z<<" "<<next.t<<" "<<endl;//
maze[next.x][next.y][next.z]='X';
q.push(next);
}
}
}
}
int main()
{
string str;
while(cin>>str){
cin>>N;
for(int i=0;i<N;i++){
for(int j=0;j<N;j++){
for(int k=0; k<N; k++){
cin>>maze[i][j][k];
}
}
}
cin>>ay>>az>>ax>>by>>bz>>bx;
cin>>str;
Bfs();
if(ok==0)
cout<<"NO ROUTE"<<endl;
}
return 0;
}
总结与收获:
1.struct定义三位点与步数的应用。
2.wlk数组的使用,可以简化代码。
3.剪枝,注意初始位置。
4.Judge函数的应用。