protagonist

矩阵距离

问题 I: 矩阵距离

时间限制: 1 Sec  内存限制: 128 MB
提交: 15  解决: 7
[提交] [状态] [命题人:admin]

题目描述

给定一个N行M列的01矩阵 A,A[i][j] 与 A[k][l] 之间的曼哈顿距离定义为:
dist(A[i][j],A[k][l])=|i-k|+|j-l|

输出一个N行M列的整数矩阵B,其中:
B[i][j]=min(1≤x≤N,1≤y≤M,A[x][y]=1)⁡{dist(A[i][j],A[x][y])}
即求与每个位置曼哈顿距离最近的1
N,M≤1000。

 

输入

第一行两个整数n,m(0 <m,n <=1000)。
接下来一个N行M列的01矩阵,数字之间没有空格。

 

输出

一个N行M列的矩阵B,相邻两个整数之间用一个空格隔开。

 

样例输入

3 4
0001
0011
0110

样例输出

3 2 1 0
2 1 0 0
1 0 0 1
#include <bits/stdc++.h>

using namespace std;
const int maxn=1100;
struct node{
     int x,y;
};
int sx[8]={0,1,-1,0,0},sy[8]={0,0,0,1,-1},n,m,dis[maxn][maxn],p[maxn][maxn];
queue<node>q;
int main()
{
    scanf("%d%d",&n,&m);
    char temp;
    for(int i=1;i<=n;i++){
        for(int j=1;j<=m;j++){
            while( ( temp =  getchar() ) != '1' && temp != '0' );
            p[i][j]=temp-'0';
            dis[i][j]=-1;
            if(p[i][j]){
                q.push(node{i,j});
                dis[i][j]=0;
            }
        }
    }
    /*for(int i=1;i<=n;i++){
        for(int j=1;j<=m;j++){
            cout<<p[i][j]<<' ';
        }
        cout<<endl;
    }*/
    while(q.size()){
         node cur=q.front();
         q.pop();
         for(int i=1;i<=4;i++){
               int dx=cur.x+sx[i],dy=cur.y+sy[i];
               if(dx>=1&&dx<=n&&dy>=1&&dy<=m&&dis[dx][dy]==-1){
                    dis[dx][dy]=dis[cur.x][cur.y]+1;
                    q.push(node{dx,dy});
               }
         }
    }
    for(int i=1;i<=n;i++){
        for(int j=1;j<=m;j++){
            if(j!=1) cout<<' ';
            cout<<dis[i][j];
        }
        cout<<endl;
    }
    return 0;
}

 

posted @ 2019-03-19 12:32  czy-power  阅读(1726)  评论(0编辑  收藏  举报