您的位置:首页 > 其它

UVA 11624

2015-08-08 17:42 686 查看
题意为,给出一个矩阵,里面有一个或者多个起火点(F),一个人的位置(J),火势可以向四周蔓延,这个人可以向四个方向逃走,无论是火还是人,都不能过墙(#),问这个人是否可以逃出这个矩阵,如果可以,求出最短时间。

思路为

1.BFS求出火蔓延到每个点的时间。

2.BFS求是否可以到达矩阵边界(如果火比人早到达,或者同时到达,那么这个位置是不能走的)。

#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<cmath>
#include<queue>
using namespace std;

const int N = 1010;
const int MAX = 2000000000;
const int dir[4][2] = {1, 0, -1, 0, 0, 1, 0, -1};
char maze

;
int fvis

;
bool pvis

;

struct Node
{
int y, x, dep;
Node ( int yy = 0, int xx = 0, int ddep = 0 ) : y ( yy ), x ( xx ), dep ( ddep ) {}
};
void init(int ey,int ex)
{
for ( int i = 0; i < ey; i++ )
for ( int j = 0; j < ex; j++ )
fvis[i][j] = MAX;
memset ( pvis, 0, sizeof ( pvis ) );
}
//bfs搜索火最短到达的时间
void bfs1 ( int ey, int ex ) // ey ex是边长
{
init(ey,ex);
queue<Node> q;
for ( int i = 0; i < ey; i++ )
for ( int j = 0; j < ex; j++ )
if ( maze[i][j] == 'F' )
{
q.push ( Node ( i, j, 0 ) );
fvis[i][j] = 0;
}
Node t;
while ( !q.empty() )
{
t = q.front();
q.pop();
for ( int i = 0; i < 4; i++ )
{
int ny = t.y + dir[i][0];
int nx = t.x + dir[i][1];
if ( ny >= 0 && nx >= 0 && nx < ex && ny < ey && maze[ny][nx] != '#' && fvis[ny][nx] == MAX )
{
fvis[ny][nx] = t.dep + 1;
q.push ( Node ( ny, nx, t.dep + 1 ) );
}
}
}
}
int bfs2 ( int oy, int ox, int ey, int ex ) //oy ox 是搜索起点, ey ex 是边长
{
Node t ( oy, ox, 0 );
pvis[oy][ox] = 1;
queue<Node> q;
q.push ( t );
while ( !q.empty() )
{
t = q.front();
q.pop();
if ( t.y == 0 || t.x == 0 || t.y == ey - 1 || t.x == ex - 1 )
return t.dep + 1;
for ( int i = 0; i < 4; i++ )
{
int ny = t.y + dir[i][0];
int nx = t.x + dir[i][1];
if ( ny >= 0 && nx >= 0 && nx < ex && ny < ey && maze[ny][nx] == '.' && t.dep + 1 < fvis[ny][nx] && pvis[ny][nx] == 0 )
{
pvis[ny][nx] = 1;
q.push ( Node ( ny, nx, t.dep + 1 ) );
}
}
}
return 0;
}
int main()
{
//freopen ( "in.txt", "r", stdin );
int t;
scanf ( "%d", &t );
while ( t-- )
{
int y, x, fy, fx, jy, jx;
scanf ( "%d%d", &y, &x );

getchar();// 吸收\n
for ( int i = 0; i < y; i++ )
{
scanf ( "%s", maze[i] );
for ( int j = 0; j < x; j++ )
if ( maze[i][j] == 'J' )
{
jy = i;
jx = j;
}
}
bfs1 ( y, x );
int res = bfs2 ( jy, jx, y, x );
if ( res )
printf ( "%d\n", res );
else
printf ( "IMPOSSIBLE\n" );
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  BFS