Wannafly exchange 1 D maze 2

This problem is to give you a matrix. A lizard wants to go from (1, 1) to (n,m), but you have to stop him from going to (n,m). Then 0 in the matrix is the path, - 1 is the wall, (1, 1e9) for the cost of turning this road into a wall, let you block his road with the minimum cost.
At the beginning of this question, I thought about dfs, but later I found that dfs couldn't. I didn't think about bfs. In fact, I added the first row and the last row to the queue, and then I looked at the minimum cost of getting to the last row or the first row first. It's a little hard to think about, but it's very simple to write

#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;
}

Posted by mrphobos on Sat, 04 Apr 2020 10:10:16 -0700