用的是廣搜,搜尋題也做了幾天了,慢慢找到點感覺了。這題沒多大變化,就是變成三維的咯。
<code>
#include<iostream>
#include<queue>
using namespace std;
#define size 15
int n;
char map[size][size][size];
bool visit[size][size][size];
int sx, sy, sz;
int ex, ey, ez;
int dir[6][3]={{0,0,-1},{0,0,1},{0,-1,0},{0,1,0},{-1,0,0},{1,0,0}};
struct Node
{
int x, y, z ;
int step;
}first,next;
bool check( int z, int y, int x)
{
if(x>=0&&x<n&&y>=0&&y<n&&z>=0&&z<n&&map[z][y][x]=='O'&&visit[z][y][x]==0)
return true;
return false;
}
void bfs()
{
int i;
queue<Node>que;
memset( visit,0,sizeof(visit) );
first.x=sx;
first.y=sy;
first.z=sz;
first.step=0;
que.push(first);
visit[first.z][first.y][first.x]=1;
if(first.x==ex && first.y==ey && first.z==ez)
{
cout<<n<<" "<<0<<endl;
return;
}
while( !que.empty() )
{
first=que.front();
que.pop();
for( i=0; i<6; i++)
{
next.x=first.x+dir[i][0];
next.y=first.y+dir[i][1];
next.z=first.z+dir[i][2];
if( check( next.z,next.y,next.x) )
{
visit[next.z][next.y][next.x]=1;
next.step=first.step+1;
if(next.x==ex && next.y==ey && next.z==ez )
{
cout<<n<<" "<<next.step<<endl;
return ;
}
que.push(next);
}
}
}
cout<<"NO ROUTE"<<endl;
}
int main()
{
int i, j, k;
char t[10];
while( scanf("%s%d",t,&n) != EOF )
{
for( i=0; i<n; i++)
for(j=0;j<n;j++)
for(k=0; k<n;k++)
cin>>map[i][j][k];
cin >> sx >> sy >> sz;
cin >> ex >> ey >> ez;
cin>>t;
memset( visit, 0, sizeof( visit) );
bfs();
}
return 0;
}