[恢]hdu 1240

2011-12-31 10:46:23

地址:http://acm.hdu.edu.cn/showproblem.php?pid=1240

题意:给n*n*n的三维迷宫,求从起点到终点的最短步数。

mark:bfs搞之。注意起点和终点也可以是'X'的情况。

代码:

# include <stdio.h>
# include <string.h>


char graph[15][15][15] ;
int step[15][15][15] ;
int q[1010][3] ;
int tab[6][3] = { {-1, 0, 0}, {1, 0, 0},
{0, -1, 0}, {0, 1, 0},
{0, 0, -1}, {0, 0, 1}} ;
int n, sx, sy, sz, ex, ey, ez ;


void bfs ()
{
int i, front = 0, rear = 1 ;
int x, y, z, xx, yy, zz ;
memset (step, -1, sizeof(step)) ;
step[sx][sy][sz] = 0 ;
q[0][0] = sx, q[0][1] = sy, q[0][2] = sz ;
while (front != rear)
{
x = q[front][0], y = q[front][1], z = q[front][2] ;
front++ ;
for (i = 0 ; i < 6 ; i++)
{
xx = x + tab[i][0] ;
yy = y + tab[i][1] ;
zz = z + tab[i][2] ;
if (xx < 0 || xx >= n ||
yy < 0 || yy >= n ||
zz < 0 || zz >= n) continue ;
if (step[xx][yy][zz] != -1) continue ;
if (xx == ex && yy == ey && zz == ez)
{
step[xx][yy][zz] = step[x][y][z]+1 ;
return ;
}
if (graph[xx][yy][zz] == 'X') continue ;
step[xx][yy][zz] = step[x][y][z] + 1 ;
q[rear][0] = xx, q[rear][1] = yy, q[rear][2] = zz ;
rear++ ;
}
}
}


int main ()
{
int i, j ;
char ss[10] ;
while (~scanf ("%s %d%*c", ss, &n))
{
for (i = 0 ; i < n ; i++)
for (j = 0 ; j < n ; j++)
scanf ("%s%*c", graph[i][j]) ;
scanf ("%d %d %d%*c", &sx, &sy, &sz) ;
scanf ("%d %d %d%*c", &ex, &ey, &ez) ;
scanf ("%s%*c", ss) ;
bfs () ;
if (step[ex][ey][ez] == -1)
puts ("NO ROUTE") ;
else printf ("%d %d\n", n, step[ex][ey][ez]) ;
}
return 0 ;
}



posted @ 2012-01-07 00:21  Seraph2012  阅读(121)  评论(0编辑  收藏  举报