E - 白银 CSU - 1726: 你经历过绝望吗?两次! 搜索

E - 白银

 CSU - 1726 

4月16日,日本熊本地区强震后,受灾严重的阿苏市一养猪场倒塌,幸运的是,猪圈里很多头猪依然坚强存活。当地15名消防员耗时一天解救围困的“猪坚强”。不过与在废墟中靠吃木炭饮雨水存活36天的中国汶川“猪坚强”相比,熊本的猪可没那么幸运,因为它们最终还是没能逃过被送往屠宰场的命运。

我们假设“猪坚强”被困在一个N*M的废墟中,其中“@”表示“猪坚强”的位置,“.”表示可以直接通过的空地,“#”表示不能拆毁的障碍物,“*”表示可以拆毁的障碍物,那么请问消防员至少要拆毁多少个障碍物,才能从废墟中救出“猪坚强”送往屠宰场?(当“猪坚强”通过空地或被拆毁的障碍物移动到废墟边缘时,视作被救出废墟)

Input

多组数据,第一行有一个整数T,表示有T组数据。(T<=100)

以下每组数据第一行有两个整数N和M。(1<=N,M<=100)

接着N行,每行有一个长度为M的字符串。

Output

一个整数,为最少拆毁的障碍物数量,如果不能逃离废墟,输出-1。

Sample Input

3
3 3
###
#@*
***
3 4
####
#@.*
**.*
3 3
.#.
#@#
.#.

Sample Output

1
0
-1

Hint

搜索水题,代码不难理解,就不说了

#include <iostream>
#include <cstring>
#include <cstdio>
#include <string>
#include <map>
#include <set>
#include <queue>
#include <stack>
#include <algorithm>
#include <math.h>

typedef long long LL;
typedef long double LD;
using namespace std;
const int  maxn=111;
char ma[maxn][maxn];
int vis[maxn][maxn];
//int f[8][2]={{-1,-1},{-1,0},{-1,1},{0,-1},{0,1},{1,-1},{1,0},{1,1}};
int f[4][2]={{-1,0},{1,0},{0,-1},{0,1}};
int N,M,T;
struct node
{
    int x,y;
    int step;
    friend bool operator <(node a,node b)
    {
        return a.step>b.step;
    }
};
priority_queue<node>q;
bool OK(int x,int y)
{
    if(x>=0&&y>=0&&x<N&&y<M)
        return true;
    return false;
}
void bfs(node st)
{
    q.push(st);
    while(!q.empty())
    {
        node t=q.top();
       
        q.pop();
        for(int i=0;i<4;i++)
        {
            int xx=t.x+f[i][0];
            int yy=t.y+f[i][1];
            if(!OK(xx,yy))
            {
                printf("%d\n",t.step);
                return;
            }
            if(vis[xx][yy]==0&&ma[xx][yy]!='#')
            {
                char ch=ma[xx][yy];
                if(ch=='*'){
                    q.push((node){xx,yy,t.step+1});
                    vis[xx][yy]=1;
                }
                if(ch=='.')
                {
                    q.push((node){xx,yy,t.step});
                    vis[xx][yy]=1;
                }
            }
        }
    }
    printf("-1\n");
}
int main()
{
    int T;
    scanf("%d",&T);
    while(T--)
    {scanf("%d%d%d",&N,&M);
        memset(vis,0,sizeof(vis));
        for(int i=0;i<N;i++)
            scanf("%s",ma[i]);
        while(!q.empty())q.pop();
        for(int i=0;i<N;i++)
        {
            for(int j=0;j<M;j++)
            {
                if(ma[i][j]=='@'){
                    bfs((node){i,j,0});
                    break;
                }
            }
        }
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/liyang__abc/article/details/81364504