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

【题目链接】:http://hihocoder.com/problemset/problem/1478

【题意】

【题解】

一开始把所有的水域的位置都加入到队列中去;
然后跑一个bfs.
第一次到达的位置肯定是最短路的;

【Number Of WA

0

【完整代码】

#include <bits/stdc++.h>
using namespace std;
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
#define LL long long
#define rep1(i,a,b) for (int i = a;i <= b;i++)
#define rep2(i,a,b) for (int i = a;i >= b;i--)
#define mp make_pair
#define pb push_back
#define fi first
#define se second
#define ms(x,y) memset(x,y,sizeof x)

typedef pair<int,int> pii;
typedef pair<LL,LL> pll;

const int dx[9] = {0,1,-1,0,0,-1,-1,1,1};
const int dy[9] = {0,0,0,-1,1,-1,1,-1,1};
const double pi = acos(-1.0);
const int N = 880;

int n,m,a[N][N],dis[N][N];
char s[N];
queue <pii> dl;

int main()
{
    //freopen("F:\\rush.txt","r",stdin);
    ios::sync_with_stdio(false),cin.tie(0);//scanf,puts,printf not use
    ms(dis,255);
    cin >> n >> m;
    rep1(i,1,n)
    {
        cin >> (s+1);
        rep1(j,1,m)
        {
            a[i][j] = s[j]-'0';
            if (a[i][j]==0)
            {
                dis[i][j] = 0;
                dl.push(mp(i,j));
            }
        }
    }
    while (!dl.empty())
    {
        int x = dl.front().fi,y = dl.front().se;
        dl.pop();
        rep1(i,1,4)
        {
            int tx = x + dx[i],ty = y + dy[i];
            if (tx>=1 && tx <= n && ty>=1 && ty <= m)
            {
                if (dis[tx][ty]==-1)
                {
                    dis[tx][ty] = dis[x][y]+1;
                    dl.push(mp(tx,ty));
                }
            }
        }
    }
    rep1(i,1,n)
        rep1(j,1,m)
        {
            cout << dis[i][j];
            if (j==m)
                cout <<endl;
            else
                cout << ' ';
        }
    return 0;
}
posted @ 2017-10-04 18:44  AWCXV  阅读(129)  评论(0编辑  收藏  举报