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;
}
相关推荐
聚客AI11 小时前
🙋‍♀️Transformer训练与推理全流程:从输入处理到输出生成
人工智能·算法·llm
大怪v13 小时前
前端:人工智能?我也会啊!来个花活,😎😎😎“自动驾驶”整起!
前端·javascript·算法
惯导马工15 小时前
【论文导读】ORB-SLAM3:An Accurate Open-Source Library for Visual, Visual-Inertial and
深度学习·算法
骑自行车的码农16 小时前
【React用到的一些算法】游标和栈
算法·react.js
博笙困了17 小时前
AcWing学习——双指针算法
c++·算法
moonlifesudo17 小时前
322:零钱兑换(三种方法)
算法
NAGNIP1 天前
大模型框架性能优化策略:延迟、吞吐量与成本权衡
算法
美团技术团队1 天前
LongCat-Flash:如何使用 SGLang 部署美团 Agentic 模型
人工智能·算法
Fanxt_Ja2 天前
【LeetCode】算法详解#15 ---环形链表II
数据结构·算法·leetcode·链表
侃侃_天下2 天前
最终的信号类
开发语言·c++·算法