3 4
0001
0011
0110
3 2 1 0
2 1 0 0
1 0 0 1
#include<bits/stdc++.h> using namespace std; typedef long long ll; inline int read() { int x=0,f=1;char ch=getchar(); while(ch<‘0‘||ch>‘9‘){if(ch==‘-‘)f=-1;ch=getchar();} while(ch>=‘0‘&&ch<=‘9‘){x=x*10+ch-‘0‘;ch=getchar();} return x*f; } #define pi 3.14159265358979323846 const int INF=0x3f3f3f3f; const int mod=1e9+7; const int maxn=1e6+100; const int maxa=1e9+10; struct node{ int x,y; }; int dx[4]={-1,1,0,0}; int dy[4]={0,0,-1,1}; int a[1010][1010]; int t[1010][1010]; int n,m; queue<node>q; void inint(){ cin>>n>>m; int p; for(int i=0;i<=n;i++){ for(int j=0;j<=m;j++){ t[i][j]=1e9; } } for(int i=1;i<=n;i++){ for(int j=1;j<=m;j++){ scanf("%1d",&p); a[i][j]=p; if(p){ t[i][j]=0; node o; o.x=i; o.y=j; q.push(o); } } } } int main(){ inint(); while(!q.empty()){ for(int i=0;i<=3;i++){ int xx=q.front().x+dx[i]; int yy=q.front().y+dy[i]; if(xx>=1&&xx<=n&&yy>=1&&yy<=m){ if(!a[xx][yy]&&t[q.front().x][q.front().y]+1<t[xx][yy]){ t[xx][yy]=t[q.front().x][q.front().y]+1; node o; o.x=xx; o.y=yy; q.push(o); } } } q.pop(); } for(int i=1;i<=n;i++){ for(int j=1;j<=m;j++){ printf("%d ",t[i][j]); } printf("\n"); } }
原文:https://www.cnblogs.com/lipu123/p/13031507.html