POJ 2251 Dungeon Master

解题思路:BFS

代码
   
     
#include < iostream >
using namespace std;
char map[ 30 ][ 30 ][ 31 ];
bool visit[ 30 ][ 30 ][ 30 ];
int sx, sy, sz, ex, ey, ez, l,r,c;
int qu[ 27005 ][ 3 ];
const int dir[ 6 ][ 3 ] = { 1 , 0 , 0 , 0 , - 1 , 0 , - 1 , 0 , 0 , 0 , 1 , 0 , 0 , 0 , 1 , 0 , 0 , - 1 };
inline
bool IsOk( int & x, int & y, int & z, int d)
{
x
+= dir[d][ 0 ], y += dir[d][ 1 ], z += dir[d][ 2 ];
char ch = map[x][y][z];
if (x >= 0 && x < l && y >= 0 && y < r && z >= 0 && z < c && ch == ' . ' &&! visit[x][y][z])
return visit[x][y][z] = true ;
return false ;
}
int BFS()
{
int i,j,s,p,d,q = p = d = 0 ,x,y,z;
qu[
0 ][ 0 ] = sx, qu[ 0 ][ 1 ] = sy, qu[ 0 ][ 2 ] = sz;
visit[sx][sy][sz]
= true ;
while (p <= q)
{
d
++ ;
for (i = p,s = q;i <= q;i ++ )
for (j = 0 ;j < 6 ;j ++ )
{
x
= qu[i][ 0 ],y = qu[i][ 1 ],z = qu[i][ 2 ];
if (IsOk(x,y,z,j))
{
qu[
++ s][ 0 ] = x,qu[s][ 1 ] = y,qu[s][ 2 ] = z;
if (x == ex && y == ey && z == ez) return d;
}
}
p
= q + 1 ,q = s;
}
return - 1 ;
}

int main()
{
int i,j,k,ans;
char ch;
while (scanf( " %d %d %d " , & l, & r, & c) != EOF && (l + r + c))
{
memset(visit,
0 , sizeof (visit));
for (i = 0 ;i < l;i ++ )
for (j = 0 ;j < r;j ++ )
for (k = 0 ;k < c;k ++ )
{
cin
>> ch; map[i][j][k] = ch;
if (ch == ' S ' )sx = i,sy = j,sz = k;
else if (ch == ' E ' )map[i][j][k] = ' . ' ,ex = i,ey = j,ez = k;
}
ans
= BFS();
(ans
< 0 ) ? printf( " Trapped!\n " ):printf( " Escaped in %d minute(s).\n " , ans);
}
return 0 ;
}

 

你可能感兴趣的:(master)