hdu 1072
地址:http://acm.hdu.edu.cn/showproblem.php?pid=1072
题意:I想(从2处)逃出迷宫(3处),0是墙,1是空地。身上有定时炸弹,在第6s爆炸(只能走5步)。4处是将定时炸弹重设的工具。问它最快能否逃出迷宫。
mark:bfs。多添加一个数组标记上次到达当前位置时定时炸弹的剩余秒数。
代码:
# include <stdio.h>
# include <string.h>
int n, m ;
int graph[10][10] ;
int step[10][10] ;
int times[10][10] ;
int sx, sy, ex, ey ;
int q[1000][2] ;
void bfs ()
{
int front = 0, rear = 1 ;
int x, y, z, xx, yy, zz ;
int i, tab[4][2] = {0, 1, 0, -1, 1, 0, -1, 0} ;
q[0][0] = sx, q[0][1] = sy ;
times[sx][sy] = 5 ;
step[sx][sy] = 0 ;
while (front != rear)
{
x = q[front][0], y = q[front][1] ;
front ++ ;
z = times[x][y] ;
if (x == ex && y == ey) return ;
if (z == 0) continue ;
for (i = 0 ; i < 4 ; i++)
{
xx = x + tab[i][0] ;
yy = y + tab[i][1] ;
zz = z - 1 ;
if (xx < 0 || xx >= n || yy < 0 || yy >= m) continue ;
if (graph[xx][yy] == 0) continue ;
if (graph[xx][yy] == 4) zz = 5 ;
if (times[xx][yy] >= zz) continue ;
step[xx][yy] = step[x][y] + 1 ;
q[rear][0] = xx, q[rear][1]=yy ;
times[xx][yy] = zz ;
rear++ ;
}
}
}
int main ()
{
int T, i, j ;
scanf ("%d", &T) ;
while (T--)
{
scanf ("%d%d", &n, &m) ;
for (i = 0 ; i < n ; i++)
for (j = 0 ; j < m ; j++)
scanf ("%d", &graph[i][j]) ;
for (i = 0 ; i < n ; i++)
for (j = 0 ; j < m ; j++)
{
if (graph[i][j] == 2) sx = i, sy = j ;
if (graph[i][j] == 3) ex = i, ey = j ;
}
memset (step, -1, sizeof(step)) ;
memset (times, -1, sizeof(times)) ;
bfs () ;
printf ("%d\n", step[ex][ey]) ;
}
return 0 ;
}