173. 矩阵距离(多源BFS)

173. 矩阵距离 - AcWing题库

给定一个 N 行 M 列的 0101 矩阵 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 列的 0101 矩阵,数字之间没有空格。

输出格式

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

数据范围

1≤N,M≤1000

输入样例:
复制代码
3 4
0001
0011
0110
输出样例:
复制代码
3 2 1 0
2 1 0 0
1 0 0 1

解析 :

我们可以将所有得 1 作为起点,这样用bfs遍历即可得到任何一个点到1 得最短距离。

我们首先需将所有得1 先入栈

cpp 复制代码
#include<iostream>
#include<string>
#include<cstring>
#include<cmath>
#include<ctime>
#include<algorithm>
#include<utility>
#include<stack>
#include<queue>
#include<vector>
#include<set>
#include<math.h>
#include<map>

using namespace std;
typedef long long LL;
typedef pair<int, int> PII;
const int N = 1e3 + 5;
int n, m;
char g[N][N];
int v[N][N],d[N][N];

void bfs() {
	queue<PII>q;
	for (int i = 1; i <= n; i++) {
		for (int j = 1; j <= m; j++) {
			if (g[i][j] == '1') {
				q.push({ i,j });
				v[i][j] = 1;
			}
		}
	}

	int dx[4] = { 0,0,1,-1 }, dy[4] = { 1,-1,0,0 };
	while (!q.empty()) {
		PII t = q.front();
		q.pop();
		for (int i = 0; i < 4; i++) {
			int a = t.first + dx[i], b = t.second + dy[i];
			if (a <= 0 || a > n || b <= 0 || b > m)continue;
			if (v[a][b])continue;
			q.push({ a,b });
			v[a][b] = 1;
			d[a][b] = d[t.first][t.second] + 1;
		}
	}
}

int main() {
	cin >> n >> m;
	for (int i = 1; i <= n; i++) {
		scanf("%s", g[i] + 1);
	}
	bfs();
	for (int i = 1; i <= n; i++) {
		for (int j = 1; j <= m; j++) {
			printf("%d ", d[i][j]);
		}
		printf("\n");
	}
	return 0;
}
相关推荐
老赵聊算法、大模型备案4 分钟前
《人工智能拟人化互动服务管理暂行办法(征求意见稿)》深度解读:AI“拟人”时代迎来首个专项监管框架
人工智能·算法·安全·aigc
雪花desu4 分钟前
【Hot100-Java中等】/LeetCode 128. 最长连续序列:如何打破排序思维,实现 O(N) 复杂度?
数据结构·算法·排序算法
松涛和鸣8 分钟前
41、Linux 网络编程并发模型总结(select / epoll / fork / pthread)
linux·服务器·网络·网络协议·tcp/ip·算法
鹿角片ljp11 分钟前
力扣26.有序数组去重:HashSet vs 双指针法
java·算法
XFF不秃头24 分钟前
力扣刷题笔记-合并区间
c++·笔记·算法·leetcode
巧克力味的桃子1 小时前
学习笔记:查找数组第K小的数(去重排名)
笔记·学习·算法
星云POLOAPI1 小时前
大模型API调用延迟过高?深度解析影响首Token时间的五大因素及优化方案
人工智能·python·算法·ai
88号技师1 小时前
2026年1月一区SCI-波动光学优化算法Wave Optics Optimizer-附Matlab免费代码
开发语言·算法·数学建模·matlab·优化算法
明朝百晓生2 小时前
强化学习[chapter8] [page17] Value Function Methods
人工智能·算法
POLITE32 小时前
Leetcode 56.合并区间 JavaScript (Day 6)
算法·leetcode·职场和发展