csu1726 你经历过绝望吗?两次!

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

这道题是BFS模板题,只是在结构体中加一个优先队列即可

#include <iostream>
#include <cstdio>
//#include <bits/stdc++.h>
#include <algorithm>
#include <cstring>
#include <queue>
using namespace std;
struct node
{
    int x,y,step;
    bool operator<(const node &i) const {
        return step>i.step;//用的破墙次数少的优先出队
    }
};
char mp[105][105];
int vis[105][105];
int n,m,sx,sy,ex,ey;
int dx[4]={-1,1,0,0},dy[4]={0,0,-1,1};
priority_queue<node> Q;
int BFS()
{
    while(!Q.empty()) Q.pop();
    node p,q;
    p.x=sx;
    p.y=sy;
    p.step=0;
    Q.push(p);
    vis[sx][sy]=1;
    int nx,ny;
    while(!Q.empty())
    {
        p=Q.top();
        Q.pop();
        if(p.x==n-1||p.x==0||p.y==m-1||p.y==0) return p.step;
        for(int i=0;i<4;i++)
        {
            nx=p.x+dx[i];
            ny=p.y+dy[i];
            if(mp[nx][ny]=='#') continue;
            //printf("%c %d",mp[nx][ny],p.step);
            //if(nx==n-1||nx==0||ny==m-1||ny==0) return p.step;
            if(mp[nx][ny]=='.'&&!vis[nx][ny])
            {
                q.x=nx;
                q.y=ny;
                q.step=p.step;
                vis[nx][ny]=1;
                Q.push(q);
               // printf("--%c--",mp[nx][ny]);

            }
            if(mp[nx][ny]=='*'&&!vis[nx][ny])
            {
                q.x=nx;
                q.y=ny;
                q.step=p.step+1;
                vis[nx][ny]=1;
                Q.push(q);
                //printf("--%c--",mp[nx][ny]);
                //if(nx>=n||nx<0||ny>=m||ny<0) return p.step;
            }

        }

    }
    return -1;
}

int main()
{
    int t;
    scanf("%d",&t);
    while(t--){
        scanf("%d%d",&n,&m);
        memset(vis,0,sizeof(vis));
        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]=='@') sx=i,sy=j;

            }
        }
        printf("%d\n",BFS());
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_40620465/article/details/81603562
今日推荐