Find a nearest station

Description

Since dandelion has left the hometown so long,she finds it’s difficult to find the station in the city.So she needs you ,a clear programmer, to help her.
Now you know the map of the city, which has showed every station in the city.You are asked to find the shortest distance between every grid and the stations.You should notice that the road in dandelion’s hometown is vertical or horizontal,so the distance of two girds is defined as |x1-x2|+|y1-y2|.

Input

The input consists of several test cases. Each test case start with a line containing two number, n, m(1 <= n, m ≤ 182), the rows and the columns of city. Then n lines follow, each contain exact m characters, representing the type of block in it. (0 for empty place ,1 for station).The data will contains at least one station.

Output

For every case ,print a matrix with n rows and m columns, the number in the i row and j column stands for the distance from this grid to the shortest station.

Sample Input

3 4
0001
0011
0110

Sample Output

3 2 1 0
2 1 0 0
1 0 0 1

#include <iostream>
#include <cstring>
#include <stdlib.h>
#include <cstdio>
#include <queue>
#define a 999

using namespace std;

char map[a][a];
int dis[a][a], vis[a][a];
int dir[4][2] = {1,0, -1,0, 0,1, 0,-1};
int m,n;

struct node
{
    int x,y;
};

void solve()
{
    queue<node> q;
    node next, now;
    int i,j;

    memset(dis, 0, sizeof(dis));
    memset(vis, 0, sizeof(vis));

    for (i = 0; i<n; i++)
    {
        scanf("%s", map[i]);
        for (j = 0; j < m; j++)
        {
            if (map[i][j] == '1')
            {

                now.x = i; now.y = j;
                q.push(now); //push the node now into the queue
                vis[i][j] = 1;
            }
        }
    }

    while (!q.empty())
    {
        now = q.front();
        q.pop();

        for(i = 0; i<4; i++)
        {
            next.x = now.x + dir[i][0];
            next.y = now.y + dir[i][1];

            if (next.x > n || next.x < 0 || next.y > m || next.y < 0)
                continue;
            if (vis[next.x][next.y])
                continue;

            q.push(next);
            dis[next.x][next.y] = dis[now.x][now.y] + 1;//retrodict
            vis[next.x][next.y] = 1;

        }
    }
}

int main(){

    int i,j;

    while (scanf ("%d%d", &n, &m) != -1)
    {
        solve();
        for(i = 0; i < n; i++)
        {
            printf("%d", dis[i][0]);
            for(j = 1; j < m; j++)
            {
                printf(" %d", dis[i][j]);
            }
            printf("\n");
        }
    }



    return 0;
}
發佈了55 篇原創文章 · 獲贊 3 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章