给定一个 N 行 M 列的 01 矩阵 A,A[i][j] 与 A[k][l]之间的曼哈顿距离定义为:
输出一个 N行 M 列的整数矩阵 B,其中:
输入格式
第一行两个整数 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;
}
}