三维矩阵的BFS思想挺简单
可是在建图的过程中有一点没想到
结果WA了4次啊,,,,,,
注意这样才正确
for(int i=1;i<=n;i++)
for(int k=1;k<=n;k++)
for(int p=1;p<=n;p++)
cin>>map[p][k][i];
而这样就不对了
for(int i=1;i<=n;i++)
for(int k=1;k<=n;k++)
for(int p=1;p<=n;p++)
cin >>map[i][k][p];
如此的三重循环 i,k,p,分别代表空间 直角坐标系的z轴,y轴,x轴
#include<cstdio>
#include<iostream>
#include<cstring>
#include <cstdlib>
#include<queue>
using namespace std;
const int N=15 ;
typedef struct node
{
int x,y,z,step;
}coord;
coord s,e;
bool used[N][N][N];
char map[N][N][N], str[10];
int n,dir[6][3]={1,0,0,-1,0,0,0,1,0,0,-1,0,0,0,1,0,0,-1};
void gchar( char &c )
{while( cin>>c, c!= 'O'&& c!= 'X' ) ;}
inline int isend(coord p)
{
if(p.x==e.x&&p.y==e.y&&p.z==e.z)
return 1;
else
return 0;
}
int BFS()
{
memset(used,0,sizeof(used));
s.step=0;
used[s.x][s.y][s.z]=1;
coord now,next;
queue<coord>Q;
Q.push(s);
while(!Q.empty())
{
now=Q.front();
Q.pop();
if( now.x== e.x&& now.y== e.y&& now.z== e.z )
return now.step;
for(int i=0;i<6;i++)
{
next.x=now.x+dir[i][0];
next.y=now.y+dir[i][1];
next.z=now.z+dir[i][2];
next.step=now.step+1;
if(map[next.x][next.y][next.z]== 'O'&& !used[next.x][next.y][next.z])
{
used[next.x][next.y][next.z]=1;
Q.push(next);
}
}
}
return -1;
}
int main ()
{
while(cin>>str>>n)
{
memset(map,0,sizeof(map));
for(int i=1;i<=n;i++)
for(int k=1;k<=n;k++)
for(int p=1;p<=n;p++)
gchar(map[p][k][i]);
cin>>s.x>>s.y>>s.z>>e.x>>e.y>>e.z>>str;
s.x+= 1, s.y+= 1, s.z+= 1, e.x+= 1, e.y+= 1, e.z+= 1;
int ans=BFS();
if(ans>=0)
printf("%d %d\n",n,ans);
else
printf("NO ROUTE\n");
}
return 0;
}
,