【FZU - 2150】Fire Game(bfs)

--> Fire Game

直接寫中文了node

Descriptions:ios

兩個熊孩子在n*m的平地上放火玩,#表示草,兩個熊孩子分別選一個#格子點火,火能夠向上向下向左向右在有草的格子蔓延,點火的地方時間爲0,蔓延至下一格的時間依次加一。求燒完全部的草須要的最少時間。如不能燒完輸出-1。數組

Input測試

第一行,輸入一個T,表示有T組測試數據。 每組數據由一個n,m分別表示行列spa

1 <= T <=100, 1 <= n <=10, 1 <= m <=10.net

Outputcode

輸出最少須要的時間

Sample Inputblog

4
3 3
.#.
###
.#.
3 3
.#.
#.#
.#.
3 3
...
#.#
...
3 3
###
..#
#.#

Sample Outputip

Case 1: 1
Case 2: -1
Case 3: 0
Case 4: 2

題目連接:ci

https://vjudge.net/problem/FZU-2150

感受仍是有必定難度的,確定是要從兩個地方開始dfs的,這兩個地方必定是乾草,同時這兩個地方能夠重疊,那麼就直接把全部的乾草所有列舉出來,每次取兩個去dfs,而後取這些dfs的最小值便可,具體操做看代碼

AC代碼

#include <iostream>
#include <cstdio>
#include <fstream>
#include <algorithm>
#include <cmath>
#include <deque>
#include <vector>
#include <queue>
#include <string>
#include <cstring>
#include <map>
#include <stack>
#include <set>
#include <sstream>
#define mod 1000000007
#define eps 1e-6
#define ll long long
#define INF 0x3f3f3f3f
#define ME0(x) memset(x,0,sizeof(x))
using namespace std;
int T,n,m,total,cnt;
char mp[15][15];//原始地圖
int vis[15][15];//記錄是否燒過
int dt[][2]= {{1,0},{-1,0},{0,1},{0,-1}};//方向
struct node
{
    int x,y;//橫縱座標
    int step;//步數
};
node now,next;
node a[15*15];//乾草座標
bool judge()//判斷草地是否所有燒完
{
    for(int i=0; i<total; i++)
        if(!vis[a[i].x][a[i].y])
            return false;
    return true;
}
int bfs(node a,node b)
{
    int steps=0;//初始步數爲0
    ME0(vis);
    queue<node>q;
    q.push(a),q.push(b);
    vis[a.x][a.y]=1,vis[b.x][b.y]=1;
    while(!q.empty())
    {
        now=q.front();
        q.pop();
        for(int i=0; i<4; i++)//分4個方向測試
        {
            next.x=now.x+dt[i][0];
            next.y=now.y+dt[i][1];
            next.step=now.step+1;
            //是否知足條件
            if(next.x>=0&&next.x<n&&next.y>=0&&next.y<m&&mp[next.x][next.y]=='#'&&!vis[next.x][next.y])
            {
                vis[next.x][next.y]=1;
                steps=max(steps,next.step);
                q.push(next);
            }
        }
    }
    if(judge())//判斷
        return steps;
    else
        return INF;
}
int main()
{
    cnt=1;//第幾組測試數據
    cin>>T;
    while(T--)
    {
        total=0;//有多少乾草
        cin>>n>>m;
        for(int i=0; i<n; i++)
        {
            for(int j=0; j<m; j++)
            {
                cin>>mp[i][j];
                if(mp[i][j]=='#')//把乾草存入數組
                {
                    a[total].x=i;
                    a[total].y=j;
                    a[total++].step=0;
                }
            }
        }
        int ans=INF;
        for(int i=0; i<total; i++)
        {
            for(int j=i; j<total; j++)
            {
                ans=min(bfs(a[i],a[j]),ans);//每次都取步數最小的值
            }
        }
//        for(int i=0; i<total; i++)
//            cout<<a[i].x<<" "<<a[i].y<<endl;
        printf("Case %d: ",cnt++);
        if(ans==INF)
            cout<<-1<<endl;
        else
            cout<<ans<<endl;
    }
}
相關文章
相關標籤/搜索