Description
给定一个由 0 和 1 组成的矩阵,找出每个元素到最近的 0 的距离。
两个相邻元素间的距离为 1 。
Input
第一行两个整数n m ( 1 ≤ n,m ≤ 100 )
接下来输入 n行 m列 的二维数组。
3 3
0 0 0
0 1 0
0 0 0
Output
输出每个元素到最近的 0 的距离。
0 0 0
0 1 0
0 0 0
Sample Input
3 3
0 0 0
0 1 0
1 1 1
Sample Output
0 0 0
0 1 0
1 2 1
思路:用bfs,将每个为0的点入队,从0的点向每个方向延伸。
代码:
#include<bits/stdc++.h>
using namespace std;
typedef pair<int,int>tp;
queue<tp>p;
int n,m;
int ans[1000][1000]; //存放答案
vector<tp>var = {tp(-1,0),tp(1,0),tp(0,1),tp(0,-1)};//四个方向
int main(){
//freopen("c://a.txt","r",stdin);
memset(ans,0,sizeof ans);
cin>>n>>m;
for(int i= 0;i< n ;i++)
for(int j = 0 ;j< m;j++){
int t;
cin>>t;
if(t == 0){ //是0就入队,1就改为-1
p.push(tp(i,j));
}
else{
ans[i][j] = -1;
}
}
while(!p.empty()){
tp f = p.front(); //取出队首元素
p.pop();
int x = f.first;
int y = f.second;
for(int i = 0 ;i< 4 ;i++){//四个方向延伸
int dx = x + var[i].first;
int dy = y + var[i].second;
if(dx>=0&&dy>=0&&dx<n&&dy<m&&ans[dx][dy] == -1){//判断周围是否有不为0的点
ans[dx][dy] = ans[x][y] + 1;
p.push(tp(dx,dy));
}
}
}
for(int i= 0;i< n ;i++){
for(int j = 0 ;j< m;j++){
cout<<ans[i][j]<<" ";
}
cout<<endl;
}
return 0;
}
end.