Cod sursa(job #983482)

Utilizator FlameingoAiordachioaei Marius Flameingo Data 11 august 2013 21:59:12
Problema Barbar Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.44 kb
#include <cstdio>
#include <queue>
#include <algorithm>
using namespace std;

const int NMAX = 1003, INFI = 2e9;

queue <pair <int, int> > q;
int D[NMAX][NMAX], L[NMAX][NMAX];
char l[NMAX];

int main () {

    freopen ("barbar.in", "r", stdin);
    freopen ("barbar.out", "w", stdout);
    int N, M, i, j, t1, t2, i1, i2, k;
    scanf ("%d%d", &N, &M);
    for (i = 1; i <= N; ++i)
        D[i][0] = D[i][M + 1] = -1,
        L[i][0] = L[i][M + 1] = INFI;
    for (i = 1; i <= M; ++i)
        D[0][i] = D[N + 1][i] = -1,
        L[0][i] = L[N + 1][i] = INFI;
    for (i = 1; i <= N; ++i) {
        scanf ("%s", l + 1);
        for (j = 1; j <= M; ++j) {
            if (l[j] == '*') {
                D[i][j] = -1;
                L[i][j] = INFI;
                continue;
            }
            if (l[j] == 'D') {
                q.push (make_pair (i, j));
                L[i][j] = INFI;
                continue;
            }
            if (l[j] == 'I') {
                i1 = i;
                i2 = j;
                continue;
            }
            if (l[j] == 'O')
                t1 = i,
                t2 = j;
        }
    }
    while (!q.empty ()) {
        i = q.front ().first;
        j = q.front ().second;
        q.pop ();
        if (!D[i - 1][j])
            D[i - 1][j] = D[i][j] + 1, q.push (make_pair (i - 1, j));
        if (!D[i][j + 1])
            D[i][j + 1] = D[i][j] + 1, q.push (make_pair (i, j + 1));
        if (!D[i + 1][j])
            D[i + 1][j] = D[i][j] + 1, q.push (make_pair (i + 1, j));
        if (!D[i][j - 1])
            D[i][j - 1] = D[i][j] + 1, q.push (make_pair (i, j - 1));
    }
    q.push (make_pair (i1, i2));
    L[i1][i2] = D[i1][i2];
    while (!q.empty ()) {
        i = q.front ().first;
        j = q.front ().second;
        q.pop ();
        k = min (L[i][j], D[i - 1][j]);
        if (L[i - 1][j] < k)
            L[i - 1][j] = k, q.push (make_pair (i - 1, j));
        k = min (L[i][j], D[i][j + 1]);
        if (L[i][j + 1] < k)
            L[i][j + 1] = k, q.push (make_pair (i, j + 1));
        k = min (L[i][j], D[i + 1][j]);
        if (L[i + 1][j] < k)
            L[i + 1][j] = k, q.push (make_pair (i + 1, j));
        k = min (L[i][j], D[i][j - 1]);
        if (L[i][j - 1] < k)
            L[i][j - 1] = k, q.push (make_pair (i, j - 1));
    }
    if (!L[t1][t2])
        printf ("-1");
    else
        printf ("%d", L[t1][t2]);

}