173. 矩阵距离
如果每个点都搜一遍一定会超时,所以需要将所有的1全部入队,再进行宽搜,这样记录的距离就是每个点到最近的1的最短距离
#include <iostream>
#include <cstring>
#include <queue>
#include <algorithm>
using namespace std;
const int N = 1e3 + 5, INF = 0x3f3f3f3f;
typedef pair<int, int> P;
queue<P> que;
char ma[N][N];
int d[N][N];
int dx[] = {0, 0, 1, -1};
int dy[] = {1, -1, 0, 0};
int n, m;
void bfs()
{
while (que.size()){
P p = que.front(); que.pop();
for (int i = 0 ; i < 4; i++){
int nx = p.first + dx[i];
int ny = p.second + dy[i];
if (nx >= 0 && nx < n && ny >= 0 && ny < m && d[nx][ny] == INF){
que.push(P(nx, ny));
d[nx][ny] = d[p.first][p.second] + 1;
}
}
}
}
int main(void)
{
memset(d, INF, sizeof d);
cin >> n >> m;
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++){
cin >> ma[i][j];
if (ma[i][j] == '1'){
que.push(P(i, j));
d[i][j] = 0;
}
}
bfs();
for (int i = 0; i < n; i++){
for (int j = 0; j < m; j++)
cout << d[i][j] << ' ';
cout << endl;
}
return 0;
}