BZOJ2252(BFS水题)

题意 给一个0 1矩阵,求每个0到最近的1的曼哈顿距离
水题 广搜即可

#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
const int N=1005;
char aa[N];
int a[N][N],ans[N][N],que[N*N][3],tx[4]={0,1,0,-1},ty[4]={1,0,-1,0},b[N][N];
int re(){
	char c=getchar();int all=0,pd=1;
	for(;c>'9'||c<'0';c=getchar()) if(c=='-') pd=-1;
	while(c>='0'&&c<='9') all=all*10+c-'0',c=getchar();return all*pd;
}
int main(){
	int n=re(),m=re();memset(ans,60,sizeof(ans));
	int head=1,tail=0;
	for(int i=1;i<=n;i++){
		scanf("%s",aa+1);
		for(int j=1;j<=m;j++){
			a[i][j]=aa[j]-'0';
			if(a[i][j]==1) que[++tail][1]=i,que[tail][2]=j,ans[i][j]=0;
		}
	}
	while(head<=tail){
		int x=que[head][1],y=que[head][2];
		for(int i=0;i<=3;i++){
			int dx=x+tx[i],dy=y+ty[i];
			if(dx>=1&&dx<=n&&dy>=1&&dy<=m&&!a[dx][dy]&&!b[dx][dy]){
				ans[dx][dy]=min(ans[dx][dy],ans[x][y]+1);
				que[++tail][1]=dx;que[tail][2]=dy;b[dx][dy]=1;
			}
		}head++;
	}for(int i=1;i<=n;i++){
		for(int j=1;j<=m;j++)
			printf("%d ",ans[i][j]);
		printf("\n");
	}
}
posted @ 2018-08-20 15:48  BLUE_EYE  阅读(304)  评论(1编辑  收藏  举报