【hihocoder [Offer收割]编程练习赛9 B】【水题】水陆距离

    xiaoxiao2021-03-25  62

    题目2 : 水陆距离

    时间限制: 10000ms 单点时限: 1000ms 内存限制: 256MB

    描述

    给定一个N x M的01矩阵,其中1表示陆地,0表示水域。对于每一个位置,求出它距离最近的水域的距离是多少。  

    矩阵中每个位置与它上下左右相邻的格子距离为1。

    输入

    第一行包含两个整数,N和M。

    以下N行每行M个0或者1,代表地图。

    数据保证至少有1块水域。

    对于30%的数据,1 <= N, M <= 100  

    对于100%的数据,1 <= N, M <= 800

    输出

    输出N行,每行M个空格分隔的整数。每个整数表示该位置距离最近的水域的距离。

    样例输入 4 4 0110 1111 1111 0110 样例输出 0 1 1 0 1 2 2 1 1 2 2 1 0 1 1 0

    #include<stdio.h> #include<iostream> #include<string.h> #include<string> #include<ctype.h> #include<math.h> #include<set> #include<map> #include<vector> #include<queue> #include<bitset> #include<algorithm> #include<time.h> using namespace std; void fre() { freopen("c://test//input.in", "r", stdin); freopen("c://test//output.out", "w", stdout); } #define MS(x, y) memset(x, y, sizeof(x)) #define ls o<<1 #define rs o<<1|1 typedef long long LL; typedef unsigned long long UL; typedef unsigned int UI; template <class T1, class T2>inline void gmax(T1 &a, T2 b) { if (b > a)a = b; } template <class T1, class T2>inline void gmin(T1 &a, T2 b) { if (b < a)a = b; } const int N = 0, M = 0, Z = 1e9 + 7, inf = 0x3f3f3f3f; template <class T1, class T2>inline void gadd(T1 &a, T2 b) { a = (a + b) % Z; } int casenum, casei; int n, m; char mp[805][805]; int f[805][805]; const int dy[4] = { -1,0,0,1 }; const int dx[4] = { 0,-1,1,0 }; int main() { while (~scanf("%d%d", &n, &m)) { for (int i = 1; i <= n; ++i) { scanf("%s", mp[i] + 1); } queue< pair<int, int> >q; for (int i = 1; i <= n; ++i) { for (int j = 1; j <= m; ++j) { f[i][j] = -1; if (mp[i][j] == '0') { f[i][j] = 0; q.push({ i,j }); } } } while (!q.empty()) { int y = q.front().first; int x = q.front().second; q.pop(); for (int i = 0; i < 4; ++i) { int yy = y + dy[i]; int xx = x + dx[i]; if (yy >= 1 && yy <= n && xx >= 1 && xx <= m && f[yy][xx] == -1) { f[yy][xx] = f[y][x] + 1; q.push({ yy, xx }); } } } for (int i = 1; i <= n; ++i) { for (int j = 1; j <= m; ++j) { printf("%d%c", f[i][j], j == m ? '\n' : ' '); } } } return 0; }

    转载请注明原文地址: https://ju.6miu.com/read-35159.html

    最新回复(0)