题目链接: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;
}
}