zoukankan      html  css  js  c++  java
  • 矩阵距离

    问题 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;
    }
  • 相关阅读:
    Sqlserver日期函数应用
    SSRS匿名访问
    SSAS动态添加分区(一)
    BI就是报表?
    CreateEvent函数/多线程/c++
    字符编码介绍
    Win7 64下Visual C++ 6.0不兼容
    Winpcap安装,Cannot open include file 'pcap.h'
    PPT开发 * .pps 文件类型
    Visual Assist X 工具栏不显示 toolbar
  • 原文地址:https://www.cnblogs.com/czy-power/p/10557848.html
Copyright © 2011-2022 走看看