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;
}
作 者: itdef
欢迎转帖 请保持文本完整并注明出处
技术博客 http://www.cnblogs.com/itdef/
B站算法视频题解
https://space.bilibili.com/18508846
qq 151435887
gitee https://gitee.com/def/
欢迎c c++ 算法爱好者 windows驱动爱好者 服务器程序员沟通交流
如果觉得不错,欢迎点赞,你的鼓励就是我的动力
欢迎转帖 请保持文本完整并注明出处
技术博客 http://www.cnblogs.com/itdef/
B站算法视频题解
https://space.bilibili.com/18508846
qq 151435887
gitee https://gitee.com/def/
欢迎c c++ 算法爱好者 windows驱动爱好者 服务器程序员沟通交流
如果觉得不错,欢迎点赞,你的鼓励就是我的动力
![阿里打赏](https://files.cnblogs.com/files/itdef/ali2.bmp)
![微信打赏](https://files.cnblogs.com/files/itdef/weixin2.bmp)