您的位置:首页 > 其它

POJ 2251 Dungeon Master BFS

2012-02-12 19:57 363 查看
这题其实是一题简单的BFS,代码注释如下程序所示:

/*
-----------------------------------------------------
Time : 19:00 - 19:53 2012.2.12
stratege : BFS
Author : Johnsondu

-----------------------------------------------------
Problem: 2251		User: a312745658
Memory: 808K		Time: 32MS
Language: G++		Result: Accepted
-----------------------------------------------------
*/

#include <iostream>
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <math.h>
#include <queue>
using namespace std ;

int direct_x[6] = {1, -1, 0, 0, 0, 0} ;	  //6个方向,分别为东南西北上下
int direct_y[6] = {0, 0, 1, -1, 0, 0} ;	  //方向很好确定,可以看到没对应一次移动
int direct_z[6] = {0, 0, 0, 0, 1, -1} ;	  //只有一个坐标发生变化

char map[35][35][35] ;

bool mark[35][35][35] ;	       //标记已走过的路程
int L, R, C ;
bool flag ;
int sx, sy, dx, dy, sz, dz ;   //确定起点和终点坐标
struct Node
{
int x ;
int y ;
int z ;
int step ;
}n, m;

int main()
{
int i, j, k ;
while (cin >> L >> R >> C)
{
if (L == 0 && R == 0 && C == 0)
break ;

for (i = 1; i <= L; i ++)
for (j = 1; j <= R ; j ++)
for (k = 1; k <= C; k ++)
{
cin >> map[i][j][k] ;
if (map[i][j][k] == 'S')
sx =  j, sy = k, sz = i ;
if (map[i][j][k] == 'E')
dz = i, dx = j, dy = k ;
}
flag = false ;

n.z = sz ;				  //初始化结构体,进队列
n.x = sx ;
n.y = sy ;
n.step = 0 ;

memset (mark, false, sizeof(mark)) ;
queue <Node> Q ;
Q.push (n) ;
mark[n.z][n.x][n.y] = true ;

while (! Q.empty())
{
m = Q.front() ;
Q.pop() ;

if (map[m.z][m.x][m.y] == 'E')	 //寻找到目标
{
flag = true ;
break ;
}

for (i = 0; i < 6; i ++)
{
n.x = m.x + direct_x[i] ;
n.y = m.y + direct_y[i] ;
n.z = m.z + direct_z[i] ;
if (n.x > 0 && n.y > 0 && n.x <= R && n.y <= C && map[n.z][n.x][n.y] != '#' && n.z > 0 && n.z <= L && mark[n.z][n.x][n.y] == false)
{							      //当且仅当满足上列条件,才允许进队列
n.step = m.step + 1 ;	      //满足条件,步数加1

mark[n.z][n.x][n.y] = true ;  //标记已走过

Q.push (n) ;
}
}
}
if (flag)
printf ("Escaped in %d minute(s).\n", m.step) ;
else
printf ("Trapped!\n") ;
}
return 0 ;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: