BZOJ 2252 矩阵距离

Posted on 2016-11-09 14:37  ziliuziliu  阅读(159)  评论(0编辑  收藏  举报

BFS。

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<queue>
#define maxn 1050
using namespace std;
int n,m,map[maxn][maxn],dis[maxn][maxn];
bool vis[maxn][maxn];
queue <int> q;
char s[maxn];
int dx[]={0,1,-1,0,0},dy[]={0,0,0,-1,1};
bool check(int x,int y)
{
    if ((x>=1) && (x<=n) && (y>=1) && (y<=m)) return true;
    return false;
}
void bfs()
{
    while (!q.empty())
    {
        int hx,hy;
        hx=q.front();q.pop();hy=q.front();q.pop();
        for (int i=1;i<=4;i++)
        {
            int tx=hx+dx[i],ty=hy+dy[i];
            if ((check(tx,ty)) && (!vis[tx][ty]))
            {
                vis[tx][ty]=true;dis[tx][ty]=dis[hx][hy]+1;
                q.push(tx);q.push(ty);
            }
        }
    }
}
int main()
{
    scanf("%d%d",&n,&m);
    for (int i=1;i<=n;i++)
    {
        scanf("%s",s);
        for (int j=1;j<=m;j++) map[i][j]=s[j-1]-'0';
        for (int j=1;j<=m;j++)
            if (map[i][j])
                {vis[i][j]=true;q.push(i);q.push(j);}
     }
     bfs();
     for (int i=1;i<=n;i++)
     {
         for (int j=1;j<=m;j++)
             printf("%d ",dis[i][j]);
        printf("\n");    
    }
    return 0;
}