FZU.2150 Fire Game (BFS)

FZU.2150 Fire Game (BFS)

题意分析

有两个人玩游戏,给出一个N*M的board,board上有一些草(用#表示)和一些空白部分(用.表示)。两个人分别选取一个点放火。求最少需要多长时间,board上的草能烧完。
注意.是不能被点燃的。

可以分别记录草坪的位置,然后每次选取两个枚举,检查当前烧完需要多长时间,在所有情况中取最小的即可。

代码总览

#include <cstdio>
#include <cstring>
#include <queue>
#include <vector>
#define nmax 15
#define inf 1000000
using namespace std;
char mp[nmax][nmax];
typedef struct{
    int x;
    int y;
}point;
typedef struct{
    int x;
    int y;
    int times;
}mes;
int spx[4] = {0,1,0,-1};
int spy[4] = {1,0,-1,0};
bool visit[nmax][nmax];
int t,n,m;
int ans,tempans;
bool check(mes temp)
{
    if(temp.x <0 || temp.x >=n || temp.y < 0|| temp.y >=m || visit[temp.x][temp.y] || mp[temp.x][temp.y] == '.')
        return false;
    else return true;
}
void bfs(point a, point b)
{
    memset(visit,0,sizeof(visit));
    queue<mes> q;
    while(!q.empty()) q.pop();
    mes temp = {a.x,a.y,0},head = {b.x,b.y,0};
    visit[a.x][a.y] = true;
    visit[b.x][b.y] = true;
    tempans = 0;
    q.push(temp);q.push(head);
    while(!q.empty()){
        head = q.front();q.pop();
        if(head.times > tempans) tempans = head.times;
        temp.times = head.times+1;
        for(int i = 0;i<4;++i){
            temp.x = head.x + spx[i];
            temp.y = head.y + spy[i];
            if(check(temp)){
                visit[temp.x][temp.y] = true;
                q.push(temp);
            }
        }
    }
    for(int i = 0;i<n;++i){
        for(int j = 0;j<m;++j){
            if(mp[i][j] == '#' && visit[i][j] == false){
                tempans = inf;
                return;
            }
        }
    }
}
int main()
{
    scanf("%d",&t);
    for(int r = 1;r<=t;++r){
        vector<point> v;v.clear();
        scanf("%d %d",&n,&m);
        ans = inf;
        for(int i = 0;i<n;++i) scanf("%s",mp[i]);
        for(int i = 0;i<n;++i){
            for(int j = 0;j<m;++j){
                if(mp[i][j] == '#'){
                    v.push_back((point){i,j});
                }
            }
        }
        for(int i = 0;i<v.size();++i)
            for(int j = i;j<v.size();++j){
                bfs(v[i],v[j]);
                if(tempans < ans) ans = tempans;
            }
        printf("Case %d: %d\n",r,ans==inf?-1:ans);
    }
    return 0;
}
posted @ 2017-07-29 10:17  pengwill  阅读(119)  评论(0编辑  收藏  举报