0 1矩阵(bfs)

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.

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值