Cod sursa(job #272728)

Utilizator silvia_the_bestSilvia Pripoae silvia_the_best Data 7 martie 2009 18:38:09
Problema Barbar Scor 80
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.61 kb
#include <cstdio>
#include <algorithm>
#include <queue>
#define FIN "barbar.in"
#define FOUT "barbar.out"
#define N 1010
#define INF 1000000
using namespace std;

const int dx[] = {-1, 0, 1, 0};
const int dy[] = {0, 1, 0, -1};

int r,c, dist[N][N], d[N][N];
queue <pair <int,int> > q;
pair <int,int> b,e;

void read()
{
    char s[N];
    freopen(FIN, "r", stdin);
    scanf("%d %d\n", &r, &c);

    for (int i = 1; i <= r; ++i)
    {
        gets(s);

        for (int j = 0; s[j]; ++j)
        {
            //if (s[j] == '.')
                //d[i][j] = -1;
            d[i][j + 1] = dist[i][j + 1] = INF;
            if (s[j] == '*')
                d[i][j + 1] = -2;
            if (s[j] == 'D')
            {
                dist[i][j + 1] = 0;
                q.push( make_pair(i, j + 1) );
            }
            if (s[j] == 'I')
            {
                b = make_pair(i, j+ 1);
                d[i][j + 1] = 0;
            }
            if (s[j] == 'O')
                e = make_pair(i, j + 1);
        }
    }
}

void BFS(int V[][N], int t)
{
    pair <int, int> p1,p2;
    for (int  i = 0; i <= r; ++i)
        V[i][0] = -2;
    for (int i = 0; i <= c; ++i)
        V[0][i] = -2;
    while (!q.empty())
    {
        p1 = q.front();
        q.pop();
        for (int i = 0; i < 4; ++i)
        {
            p2 = make_pair(p1.first + dx[i], p1.second + dy[i]);
            if (t == 1 && d[p2.first][p2.second] != -2 && V[p2.first][p2.second] > V[p1.first][p1.second] + 1)
            {
                V[p2.first][p2.second] = V[p1.first][p1.second] + 1;
                q.push(p2);
            }
            if (t == 2 &&  d[p2.first][p2.second] != -2 && (V[p2.first][p2.second] == INF || (dist[p2.first][p2.second] >= V[p1.first][p1.second] && V[p2.first][p2.second] < V[p1.first][p1.second])))
            {
                V[p2.first][p2.second] =  min(dist[p2.first][p2.second], V[p1.first][p1.second]);
                q.push(p2);
            }
        }
    }
}

void write()
{
    freopen(FOUT, "w", stdout);
    if (d[e.first][e.second] != INF)
        printf("%d\n", d[e.first][e.second]);
    else
        printf("-1\n");
}

/*void write2()
{
    freopen(FOUT, "w", stdout);
    for (int i = 1; i <= r; ++i)
    {
        for (int j = 1; j <= c; ++j)
            printf("%d ",d[i][j]);
        printf("\n");
    }
    printf("%d (%d %d)\n", d[e.first][e.second], e.first, e.second);
}*/

int main()
{
    read();

    BFS(dist, 1);

    q.push(b);
    d[b.first][b.second] = dist[b.first][b.second];

    BFS(d, 2);

    write();
}