173 矩阵距离


// 173. 矩阵距离.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//

#include <iostream>
#include <queue>
#include <vector>

using namespace std;

/*

https://www.acwing.com/problem/content/175/
给定一个 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
*/


const int N = 1010;
int gra[N][N];
int ans[N][N];
int vis[N][N];
queue<vector<int>> q;
int n, m;


int addx[] = { 1,0,-1,0 };
int addy[] = { 0,1,0,-1 };


int main()
{
cin >> n >> m;

for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
char c; cin >> c;
if (c == '1') { gra[i][j] = 1; }
if (gra[i][j] == 1) {
q.push({ i,j ,0});
vis[i][j] = 1;
}
}
}

while (!q.empty()) {
int x = q.front()[0];
int y = q.front()[1];
int step = q.front()[2];
q.pop();

if (gra[x][y] == 0 && ans[x][y] == 0) {
ans[x][y] = step;
}
else if (gra[x][y] == 0 && ans[x][y] > step) {
ans[x][y] = step;
}

for (int i = 0; i < 4; i++) {
int newx = x + addx[i];
int newy = y + addy[i];
if (newx < n && newx >= 0 && newy < m && newy >= 0 && vis[newx][newy] == 0) {
q.push({ newx,newy,step + 1 }); vis[newx][newy] = 1;
}
}
}

for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
cout << ans[i][j] << " ";
}
cout << endl;
}


return 0;
}

 

posted on   itdef  阅读(11)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
· 25岁的心里话
历史上的今天:
2020-07-19 LeetCode 1520. 子树中标签相同的节点数 暴力遍历 哈希
2019-07-19 AcWing 38. 二叉树的镜像
2019-07-19 AcWing 32. 调整数组顺序使奇数位于偶数前面
2019-07-19 AcWing 13. 找出数组中重复的数字
2016-07-19 黑客屏保 代码来自网络搜索 做了部分改动
2015-07-19 c++11日志练习

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

点击右上角即可分享
微信分享提示