//时间复杂度
O(n*n)
C++ 代码
#include<iostream>
#include<queue>
#include<cstring>
using namespace std;
const int N = 1e3 + 1;
int n, m;
char v[N][N];
int visited[N][N];
int dx[] = { -1,0,1,0 };
int dy[] = { 0,1,0,-1 };
int ret[N][N];
struct node
{
int x, y, step;
};
queue<node>q;
void bfs()
{
while (!q.empty())
{
for (int a = 0; a < 4; a++)
{
int tx = q.front().x + dx[a];
int ty = q.front().y + dy[a];
if (tx<1 || tx>n || ty<1 || ty>m || v[tx][ty] == '1' || visited[tx][ty] == 1)continue;
visited[tx][ty] = 1;
node tmp;
tmp.x = tx, tmp.y = ty,tmp.step = q.front().step + 1;
ret[tx][ty] = tmp.step;
//cout << tmp.step << " ";
q.push(tmp);
}
q.pop();
}
}
int main()
{
cin >> n >> m;
//1是源点,0是终点,求达到所有终点要多少步
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= m; j++)
{
cin >> v[i][j];
if (v[i][j] == '1')
//源点步数为0
{
q.push({ i,j,0 });
visited[i][j] = 1;
}
}
}
bfs();
for (int i = 1; i <= n; i++)
{
for (int j=1; j <= m; j++)
{
cout << ret[i][j] << " ";
}
cout << endl;
}
return 0;
}