2020 camp-day-

bfs

#include <cstdio>
#include <utility>
#include <queue>

#define RE register
#define FOR(i,a,b) for(RE int i=a;i<=b;++i)
#define ROF(i,a,b) for(RE int i=a;i>=b;--i)
#define P pair<int,int>
#define sc(n) scanf("%d",&n)

using namespace std;

const int maxn = 102;

struct Horse
{
    P p; int c = 0;
}horse;

int mp[maxn][maxn], ans[maxn][maxn], n, m;
int d[][2] = { {1,2},{-1,2},{1,-2},{-1,-2},{2,1},{2,-1},{-2,1},{-2,-1} };
char s[maxn];
queue<Horse> qu;

inline bool check(int k)
{
    P p = horse.p; p.first += d[k][0], p.second += d[k][1];
    if (p.first<1 || p.first>n || p.second<1 || p.second>m || mp[p.first][p.second])return false;
    if (k < 2) { if (mp[horse.p.first][horse.p.second + 1] == 2)return false; }
    else if (k < 4) { if (mp[horse.p.first][horse.p.second - 1] == 2)return false; }
    else if (k < 6) { if (mp[horse.p.first + 1][horse.p.second] == 2)return false; }
    else if (mp[horse.p.first - 1][horse.p.second] == 2)return false;
    return true;
}

int main()
{
    sc(n); sc(m);
    FOR(i, 1, n)
    {
        scanf("%s", s + 1);
        FOR(j, 1, m)
        {
            ans[i][j] = -1;
            if (s[j] == '.');
            else if (s[j] == 'M')horse.p = { i,j }, mp[i][j] = 1, qu.push(horse), ans[i][j] = 0;
            else mp[i][j] = 2;
        }
    }
    while (!qu.empty())
    {
        horse = qu.front(); qu.pop();
        FOR(i, 0, 7)
            if (check(i))
            {
                Horse h = horse; h.p.first += d[i][0], h.p.second += d[i][1]; ++h.c; qu.push(h);
                mp[h.p.first][h.p.second] = 1; ans[h.p.first][h.p.second] = h.c;
            }
    }
    FOR(i, 1, n - 1)
    {
        FOR(j, 1, m - 1)printf("%d ", ans[i][j]);
        printf("%d\n", ans[i][m]);
    }
    FOR(j, 1, m - 1)printf("%d ", ans[n][j]);
    printf("%d", ans[n][m]);
    return 0;
}

  

posted @ 2020-01-20 09:49  洛绫璃  阅读(180)  评论(0编辑  收藏  举报