您的位置:首页 > 其它

FZU2150->BFS

2016-08-17 10:52 260 查看

FZU2150->BFS

题意:

有一片草地,两个人同时放火烧草地,点燃一片草地后,火会向四周蔓延,求最少要多久能把所有草地都烧完

题解:

先预处理,记录所有能放火的地点,然后把这些地点两两分别组合,通过BFS的方式判断是否能烧完草地,以及烧完草地要走多少步,最后选出最少的步数

代码:

#include <stdio.h>
#include <iostream>
#include <string.h>
#include <queue>
using namespace std ;
#define INF 0x3f3f3f3f
#define MAX 110007
int n, m, cnt, t;
char Map[20][20] ;
int visit[20][20] ;
int dir[4][2] = {{0 , 1} , {1 , 0} , {0 , -1} , {-1 , 0}};
struct node
{
int x , y , step ;
}s[500];
int judge()
{
for(int i = 0 ; i < n ; i ++)
{
for(int j = 0 ; j < m ; j ++)
{
if(Map[i][j] == '#'&& !visit[i][j])
return 0 ;
}
}
return 1 ;
}
int BFS(node s , node e)
{
queue<node> Q ;
Q.push(s) ;
Q.push(e) ;
visit[s.x][s.y] = 1 ;
visit[e.x][e.y] = 1 ;
node q ;
while(!Q.empty())
{
q = Q.front() ;
Q.pop() ;
for(int i = 0 ; i < 4 ; i ++)
{
node k ;
k.x = q.x + dir[i][0];
k.y = q.y + dir[i][1];
if(k.x>=0 && k.x<n && k.y>=0 && k.y<m && Map[k.x][k.y]=='#' && !visit[k.x][k.y])
{
visit[k.x][k.y] = 1;
k.step = q.step + 1;
Q.push(k);
}
}
}
return q.step;
}
void solve()
{
int i, j, ans;
ans = INF;
for(i=0; i<cnt; i++)
for(j=i; j<cnt; j++)
{
memset(visit, 0, sizeof(visit));
int L = BFS(s[i], s[j]);

if(L < ans && judge())
ans = L;
}

if(ans == INF)
printf("Case %d: -1\n", t++);
else
printf("Case %d: %d\n", t++, ans);
}
int main()
{
int T ;
t = 1 ;
scanf("%d" , &T) ;
while(T --)
{
scanf("%d%d" , &n , &m) ;
for(int i = 0 ; i < n ; i ++)
scanf("%s" , Map[i]) ;
cnt = 0 ;
for(int i = 0 ; i < n ; i ++)
{
for(int j = 0 ; j < m ; j ++)
{
if(Map[i][j] == '#')
{
s[cnt].x = i ;
s[cnt].y = j ;
s[cnt].step = 0 ;
cnt ++ ;
}
}
}
solve() ;
}
return 0 ;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: