Dungeon Master--POJ 2251

1、题目类型:模拟、迷宫、BFS。

2、解题思路:BFS的三维Maze[][][]应用,其每步存在前后、左右、上下6个方向的选择。

3、注意事项:BFS入队列的条件判断。

4、实现方法:

  
    
#include < iostream >
#include
< queue >
using namespace std;

struct Point
{
int x,y,z;
int step;
};

Point start,end;
int dir[ 6 ][ 3 ] = {{ - 1 , 0 , 0 },{ 1 , 0 , 0 },{ 0 , - 1 , 0 },
{
0 , 1 , 0 },{ 0 , 0 , - 1 },{ 0 , 0 , 1 }};
int x,y,z;
char Maze[ 50 ][ 50 ][ 50 ];
void Init()
{
int i,j,k;
for (i = 0 ;i < x;i ++ )
{
for (j = 0 ;j < y;j ++ )
{
for (k = 0 ;k < z;k ++ )
{
cin
>> Maze[i][j][k];
if (Maze[i][j][k] == ' S ' )
{
start.x
= i;
start.y
= j;
start.z
= k;
}
if (Maze[i][j][k] == ' E ' )
{
end.x
= i;
end.y
= j;
end.z
= k;
}
}
}
}
}

void BFS()
{
queue
< Point > Q;
int vis[ 50 ][ 50 ][ 50 ];
memset(vis,
0 , sizeof (vis));
start.step
= 0 ;
Q.push(start);
vis[start.x][start.y][start.z]
= 1 ;
while ( ! Q.empty())
{
Point p
= Q.front();
Q.pop();
if (p.x == end.x && p.y == end.y && p.z == end.z)
{
cout
<< " Escaped in " << p.step << " minute(s). " << endl;
return ;
}
for ( int i = 0 ;i < 6 ;i ++ )
{
int x1,y1,z1;
x1
= p.x + dir[i][ 0 ];
y1
= p.y + dir[i][ 1 ];
z1
= p.z + dir[i][ 2 ];
if (x1 >= 0 && x1 < x && y1 >= 0 && y1 < y && z1 >= 0 && z1 < z &&! vis[x1][y1][z1] && Maze[x1][y1][z1] != ' # ' )
{
Point tmp;
tmp.x
= x1;
tmp.y
= y1;
tmp.z
= z1;
tmp.step
= p.step + 1 ;
vis[x1][y1][z1]
= 1 ;
Q.push(tmp);
}
}
}
cout
<< " Trapped! " << endl;
return ;
}

int main()
{
while (cin >> x >> y >> z)
{
if (x == 0 && y == 0 && z == 0 )
break ;
Init();
BFS();
}
return 0 ;
}

 

你可能感兴趣的:(master)