N行M列的01矩阵
其中1为起点
求出从起点到0的最短距离
1 <= N,M <= 1000
思路:将所有起点入队,即为1的点,然后进行BFS
#include <iostream>
#include <cstdio>
#include <queue>
using namespace std;
const int N = 1010;
int n,m;
char g[N][N];
int dis[N][N];
int dx[10] = {0,0,-1,1},dy[10] = {-1,1,0,0};
void bfs()
{
queue<int> x,y;
for(int i = 0;i < n;i ++)
for(int j = 0;j < m;j ++)
if(g[i][j] == '1')
{
x.push(i),y.push(j);
dis[i][j] = 0;
}
while(x.size())
{
int hx = x.front(),hy = y.front();
for(int i = 0;i < 4;i ++)
{
int nx = hx + dx[i],ny = hy + dy[i],ns = dis[hx][hy] + 1;
if(nx >= 0 && nx < n && ny >= 0 && ny < m && g[nx][ny] == '0' && !dis[nx][ny])
{
x.push(nx),y.push(ny);
dis[nx][ny] = ns;
}
}
x.pop(),y.pop();
}
}
int main()
{
cin >> n >> m;
for(int i = 0;i < n;i ++)
scanf("%s",g[i]);
bfs();
for(int i = 0;i < n;i ++)
{
for(int j = 0;j < m;j ++)
printf("%d ",dis[i][j]);
cout << endl;
}
return 0;
}