Cod sursa(job #2234991)

Utilizator alextodoranTodoran Alexandru Raul alextodoran Data 26 august 2018 12:51:48
Problema Barbar Scor 80
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.2 kb
#include <bits/stdc++.h>

#define NM 1002
#define INF 1000000002

using namespace std;

int n, m;

char c[NM][NM];
bool ma[NM][NM];
int sa, sb, fa, fb;

int Ddist[NM][NM];
int mi[NM][NM];

queue < pair <int, int> > q;

int da[] = {-1, 0, 1, 0}, db[] = {0, 1, 0, -1};

bool isok(int a, int b)
{
    return (a >= 1 && a <= n && b >= 1 && b <= m);
}

void Dbfs(int a, int b)
{
    q.push(make_pair(a, b));
    Ddist[a][b] = 0;
    while(!q.empty())
    {
        pair <int, int> f = q.front();
        q.pop();
        for(int i = 0; i < 4; i++)
        {
            int f1 = f.first + da[i], f2 = f.second + db[i];
            if(isok(f1, f2) && ma[f1][f2] == 0 && Ddist[f1][f2] > Ddist[f.first][f.second] + 1)
            {
                q.push(make_pair(f1, f2));
                Ddist[f1][f2] = Ddist[f.first][f.second] + 1;
            }
        }
    }
}

void bfs(int a, int b)
{
    q.push(make_pair(a, b));
    mi[a][b] = Ddist[a][b];
    while(!q.empty())
    {
        pair <int, int> f = q.front();
        q.pop();
        for(int i = 0; i < 4; i++)
        {
            int f1 = f.first + da[i], f2 = f.second + db[i];
            if(isok(f1, f2) && ma[f1][f2] == 0 && mi[f1][f2] < min(mi[f.first][f.second], Ddist[f1][f2]))
            {
                q.push(make_pair(f1, f2));
                mi[f1][f2] = min(mi[f.first][f.second], Ddist[f1][f2]);
            }
        }
    }
}

int main()
{
    ifstream fin ("barbar.in");
    ofstream fout ("barbar.out");
    fin >> n >> m;
    for(int i = 1; i <= n; i++)
        for(int j = 1; j <= m; j++)
        {
            fin >> c[i][j];
            if(c[i][j] == '*')
                ma[i][j] = 1;
            else if(c[i][j] == 'I')
            {
                sa = i;
                sb = j;
            }
            else if(c[i][j] == 'O')
            {
                fa = i;
                fb = j;
            }
            Ddist[i][j] = INF;
            mi[i][j] = -1;
        }
    for(int i = 1; i <= n; i++)
        for(int j = 1; j <= m; j++)
            if(c[i][j] == 'D')
                Dbfs(i, j);
    bfs(sa, sb);
    fout << mi[fa][fb] << "\n";
    return 0;
}