萌新求助,60分
查看原帖
萌新求助,60分
236416
_stOrz_楼主2021/10/30 08:36
#include<bits/stdc++.h>

using namespace std;

struct node{
    int x, y, time;
}q[1000005];
struct Node{
    int x, y;
};
int Map[1005][1005], dx[5] = {0,0,0,1,-1}, dy[5] = {0,1,-1,0,0}, bu[1005][1005], mini=0x3f3f3f3f, n, m, bu2[1005][1005], sx, sy, l = 1, r = 1;
bool vis[1005][1005];

vector<Node>v;

void bfs(){
    while(l <= r){
        node now = q[l++];
        bu[now.x][now.y] = now.time;
        vis[now.x][now.y] = true;
        for(int i = 1; i <= 4; i++){
            int nx = dx[i] + now.x, ny = dy[i] + now.y;
            if(vis[nx][ny] == false and (Map[nx][ny] == 0 || Map[nx][ny] == 4) and nx >= 1 and ny <= m and nx <= n and ny >= 1){
            	if(bu[now.x][now.y]+1 >= bu[nx][ny]) continue;
            	q[++r] = ((node){nx, ny, now.time + 1});
			}
        }
    }
}
void bfs2(){
    while(l <= r){
        node now = q[l++];
        bu2[now.x][now.y] = now.time;
        vis[now.x][now.y] = true;
        for(int i = 1; i <= 4; i++){
            int nx = dx[i] + now.x, ny = dy[i] + now.y;
            if(vis[nx][ny] == false and Map[nx][ny] != 1 and nx >= 1 and ny <= m and nx <= n and ny >= 1){
            	if(bu2[now.x][now.y]+1 >= bu2[nx][ny]) continue;
            	q[++r] = ((node){nx, ny, now.time + 1});
			}
        }
    }
}
int main()
{
    memset(bu, 0x3f, sizeof(bu));
    memset(bu2, 0x3f, sizeof(bu2));
    cin >> m >> n;
    for(int i = 1;i <= n; i++){
        for(int j = 1; j <= m; j++){
            cin >> Map[i][j];
            if(Map[i][j] == 2) q[r] = ((node){i, j, 0}); 
            else if(Map[i][j] == 3) sx = i,sy = j;
            else if(Map[i][j] == 4) v.push_back((Node){i, j});
        }
    }
    vis[sx][sy]=true;
    bfs();
    memset(q, 0, sizeof(q));
    memset(vis, 0, sizeof(vis));
    l = 1, r = 1;
    q[r] = ((node){sx, sy, 0});
    bfs2();
    for(int i = 0; i < v.size(); i++){
        if(mini > bu[v[i].x][v[i].y] + bu2[v[i].x][v[i].y]) mini = bu[v[i].x][v[i].y] + bu2[v[i].x][v[i].y]; 
        //cout << v[i].x << " " << v[i].y << " " << bu[v[i].x][v[i].y] << " " << bu2[v[i].x][v[i].y] << endl;
    }
    cout << mini << endl;
}
2021/10/30 08:36
加载中...