P1332 血色先锋队 - bfs

P1332 血色先锋队

https://www.luogu.com.cn/problem/P1332

题意

  • 给定一个 N*M 的矩阵。
  • 给出 a 个点(传染源),他们每小时会向上下左右扩展一格。
  • 给出 b 个询问,询问这些点被感染的时间。

想法

  • bfs
  • 每一个传染源加入队列中。将mp数组,填上bfs的层数。也就是最小的步数
//P1332 血色先锋队
// Created by majoe on 2020/5/31.
//https://www.luogu.com.cn/problem/P1332

#include<bits/stdc++.h>
using namespace std;
int n,m,a,b;
int lz[100005][2];//lz就是领主
bool vis[505][505];
int mp[505][505];
int dx[4]={0,0,1,-1};//横轴4方向数组
int dy[4]={1,-1,0,0};//纵轴4方向数组
struct node{
    int x,y,steps;
}nodes[510];

queue<node> q;

void bfs(){
    while (!q.empty()){
        node t = q.front();
        q.pop();
        int x = t.x, y = t.y, s = t.steps;
        mp[x][y] = s;
        for (int i = 0; i < 4; ++i) { //4个方向
            int tx = x + dx[i];
            int ty = y + dy[i];
            if(tx < 1 || ty < 1 || tx >n || ty >m || vis[tx][ty]) continue;
            node nd;
            nd.steps = s + 1;
            nd.x = tx;
            nd.y = ty;
            vis[tx][ty] = 1;
            q.push(nd);
        }
    }
}
int main(){
    cin >> n >> m >> a >> b;
    //将瘟疫源头装入队列
    for (int i = 0; i < a; ++i) {
        node n;
        int x ,y;
        cin >> x >> y;
        n.x = x;
        n.y = y;
        n.steps =0;
        vis[x][y] = 1;
        q.push(n);
    }

    //保存领主的位置
    for (int i = 0; i < b; ++i) {
        cin >> lz[i][0] >> lz[i][1];
    }
    
    bfs();

    //输出领主位置
    for (int i = 0; i < b; ++i) {
        int l_x = lz[i][0], l_y = lz[i][1];
        cout << mp[l_x][l_y]<< endl;
    }

    return 0;
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值