矩阵距离—多源BFS—dis数组存距离

 给定一个 N 行 M 列的 01 矩阵 A,A[i][j] 与 A[k][l]之间的曼哈顿距离定义为:

dist(A[i][j],A[k][l])=|i−k|+|j−l|

输出一个 N行 M 列的整数矩阵 B,其中:

B[i][j]=min1≤x≤N,1≤y≤M,A[x][y]=1dist(A[i][j],A[x][y])

输入格式

第一行两个整数 N,M。接下来一个 N行 M 列的 01矩阵,数字之间没有空格。

输出格式

一个 N行 M 列的矩阵 B,相邻两个整数之间用一个空格隔开。

数据范围

1≤N,M≤1000

输入样例:

3 4
0001
0011
0110

输出样例:

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

 分析:

多源BFS

用于优化时间复杂度

类似于多源最短路,从一个起点到其他地方的最短路;

要求权重为1;

如果在每个起点搜一遍,则时间复杂度为N^2;

实现方法:把所有起点放到队列中去,按照一般宽搜方式,将其余点一层一层扩展进来。

  并且使用dis数组存储距离

#include <bits/stdc++.h>
#define endl '\n'
#define int long long
#define Bug cout<<"---------------------"<<endl
using namespace std;
typedef pair<int, int>pii;
const int N = 1010, M = N * N;
char mp[N][N];
int dis[N][N];
int m, n;
bool in(int x, int y) {
	return x >= 0 && x < m&& y >= 0 && y < n;
}
int dir[4][2] = { {-1,0},{0,1},{1,0},{0,-1}};
pii q[M];
void bfs() {
	memset(dis, -1, sizeof dis);
	int hh = 0, tt = -1;
	//放入
	for (int i = 0;i < m;i++) {
		for (int j = 0;j < n;j++) {
			if (mp[i][j] == '1') {
				q[++tt] = { i,j };
				dis[i][j] = 0;
			}
		}
	}
	while (hh <= tt) {
		pii now = q[hh++];
		for (int i = 0;i < 4;i++) {
			int tx = now.first + dir[i][0];
			int ty = now.second + dir[i][1];
			if (in(tx, ty) && dis[tx][ty] == -1 ) {
				dis[tx][ty] = dis[now.first][now.second] + 1;
				q[++tt] = { tx,ty };
			}
		}
	}
}
signed main() {
	ios_base::sync_with_stdio(0);
	cin.tie(0); cout.tie(0);
	cin >> m >> n;
	for (int i = 0;i < m;i++) {//行
		for (int j = 0;j < n;j++) {
			cin >> mp[i][j];
		}
	}
	bfs();
	for (int i = 0;i < m;i++) {
		for (int j = 0;j < n;j++) {
			cout << dis[i][j] << ' ';
		}
		cout << endl;
	}
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ou_fan

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值