多源BFS模板题

D.最近的商店(比赛中叫 不会吧不会有人觉得这不是签到吧)

Time limit:1 seconds
Memory limit:64 megabytes

​ 协会成员马上要入住算协小镇了!他们不想去一个离自己很远的商店,因此每个人都想知道离自己房子最近的商店有多远。

​ 他们向你求助,希望你能帮他们做一个标有商店距离的平面图。

​ 算协小镇上的房子严格按照n ∗ m n * mn∗m的点阵建造,其中分布有居民楼和商店,距离按照每个单元格进行计算(横与纵坐标差之和)。

输入

​ 第一行输入n nn和m mm,随后n nn行,每行m mm列,1 11代表商店,0 00代表居民楼。

输出

​ 输出一个n ∗ m n * mn∗m的矩阵,代表距离商店的平面图。(商店本身输出0 00)

保证
对于所有输入x xx(代指所有可能出现的输入),都有1 ≤ x ≤ 999 1 \le x \le 9991≤x≤999

测试样例1
input
4 5
00001
00110
01100
00010

output
3 2 1 1 0
2 1 0 0 1
1 0 0 1 2
2 1 1 0 1

多源BFS模板题,若单个查找每个起点,其时间复杂度最大为O ( ( n ∗ m ) 2 ) O((n*m)^2)O((n∗m) 2)​,因此需要一次将所有起点加入队列进行BFS查找。
#include<iostream>
#include<algorithm>
#include<string.h>
#include<stdio.h>
#include<string>
#include<queue>

using namespace std;

const int goin[4][2] = { 1,0,0,1,-1,0,0,-1 };
int n, m;
int num[1005][1005], vis[1005][1005], g[1005][1005];
queue<pair<int, int>>q;

bool pd(int x, int y) {
	return (x > -1 && y > -1 && x < n&& y < m);
}

pair<int, int> move(int x, int y, int i) {
	return {(x + goin[i][0]), (y + goin[i][1])};
}

void bfs() {
	while (!q.empty()) {
		auto [x, y] = q.front();
		q.pop();
		for (int i = 0; i < 4; i++){
			auto [x1, y1] = move(x, y, i);
			if (pd(x1, y1)){
			    if(!vis[x1][y1] && num[x1][y1] == 0) {
			    	vis[x1][y1] = 1;
				    q.emplace(x1, y1);
			    	g[x1][y1] = g[x][y] + 1;
			    }
			}
		}
	}
}

int main() {
	cin >> n >> m;
	for (int i = 0; i < n; i++) {
		for (int j = 0; j < m; j++) {
			scanf("%1d", &num[i][j]);//1d表示读几个字节
			if (num[i][j] == 1) q.emplace(i, j);
		}
	}
	bfs();
	for (int i = 0; i < n; i++) {
		cout << g[i][0];
		for (int j = 1; j < m; j++) {
			cout << ' ' << g[i][j];
		}
		cout << endl;
	}
	return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值