Wannafly交流赛1 D迷宫2

这道题是给你一个矩阵,一只蜥蜴想从(1,1)到(n,m),但你要阻止他到(n,m),然后矩阵中0为通路,-1为墙,(1,1e9)为将这条路变成墙的花费,让你用最小花费堵住他的路。
这道题刚开始想dfs,后来发现dfs不了,没往bfs上想,其实就是将第一排和最后一列加入队中,然后看最先到达最后一排或第一列的最小花费,想有点难想,不过写起来还是很简单的

#include<bits/stdc++.h>
using namespace std;
using LL = int64_t;
const int maxn=1e3+5;
const int mod=1e9+7;
const int INF=0x3f3f3f3f;
const LL LLINF=1e16;
const double pi=acos(-1.0);
LL node[maxn][maxn];
struct Node {
    LL x,y,sum;
    Node (LL xx,LL yy,LL ssum) {
        x=xx;y=yy;sum=ssum;
    }
    bool operator <(const Node &a)const {
        return sum>a.sum;
    }
};
priority_queue<Node>Q;
int n,m;
bool vis[maxn][maxn];
int cnt[4][2]={0,1,0,-1,1,0,-1,0};
bool check(int x,int y) {
    if(x>=1&&x<=n&&y>=1&&y<=m) return true;
    return false;
}

LL bfs() {
    while(!Q.empty()) Q.pop();
    for(int i=1;i<=n;i++){
        if(node[i][m]!=-1) {
            Q.push(Node(i,m,node[i][m]));
        }
    }
    for(int i=1;i<=m;i++) {
        if(node[1][i]!=-1) {
            Q.push(Node(1,i,node[1][i]));
        }
    }
    memset(vis,false,sizeof(vis));
    while(!Q.empty()) {
        Node now=Q.top();
        Q.pop();
        if(vis[now.x][now.y]==true) continue;
        vis[now.x][now.y]=true;
        if(now.x==n||now.y==1) return now.sum;
        for(int i=0;i<4;i++) {
            int tx=now.x+cnt[i][0];
            int ty=now.y+cnt[i][1];
            if(check(tx,ty)&&vis[tx][ty]==false&&node[tx][ty]>=0) {
                Q.push(Node(tx,ty,now.sum+node[tx][ty]));
            }
        }
    }
    return -1;
}

int main()
{
    int T;
    scanf("%d%d%d",&T,&n,&m);
    while(T--) {
        LL x;
        for(int i=1;i<=n;i++) {
            for(int j=1;j<=m;j++) {
                scanf("%lld",&node[i][j]);
                if(node[i][j]==0) node[i][j]=-1;
                else if(node[i][j]==-1) node[i][j]=0;
            }
        }
        printf("%lld\n",bfs());
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值