Cod sursa(job #2958288)

Utilizator cattyAninisCatrinel catty Data 25 decembrie 2022 18:05:18
Problema Barbar Scor 90
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.58 kb
#include <bits/stdc++.h>
using namespace std;
ifstream in("barbar.in");
ofstream out("barbar.out");
short n,m,i,j,d[1001][1001],di[]= {1,0,-1,0},dj[]= {0,1,0,-1},is,js,ia,ja,a[1001][1001];
char x;
struct c
{
    short a,b;
};
queue<c> q;
bool mat(short i, short j)
{
    return i>=1 && j<=m && j>=1 && i<=n;
}
void f1()
{
    while(!q.empty())
    {
        short x=q.front().a,y=q.front().b;
        for(short k=0; k<4; ++k)
        {
            short xn=x+di[k],yn=y+dj[k];
            if(mat(xn,yn) && a[xn][yn]==0 && d[xn][yn]==0)
                d[xn][yn]=d[x][y]+1,q.push({xn,yn});
        }
        q.pop();
    }
}
void f2()
{
    q.push({is,js});
    a[is][js]=d[is][js];
    while(!q.empty())
    {
        short x=q.front().a,y=q.front().b;
        for(short k=0; k<4; ++k)
        {
            short xn=x+di[k],yn=y+dj[k];
            if(mat(xn,yn) && a[xn][yn]>-1 && a[xn][yn]<min(a[x][y],d[xn][yn]))
            {
                a[xn][yn]=min(a[x][y],d[xn][yn]);
                if(xn==ia && yn==ja)
                    continue;
                else
                    q.push({xn,yn});
            }
        }
        q.pop();
    }
}
int main()
{
    in>>n>>m;
    for(i=1; i<=n; ++i)
        for(j=1; j<=m; ++j)
        {
            in>>x;
            if(x=='D')
                q.push({i,j}),a[i][j]=-1;
            else if(x=='I')
                is=i,js=j;
            else if(x=='O')
                ia=i,ja=j;
            else if(x=='*')
                a[i][j]=-1;
        }
    f1();
    f2();
    out<<a[ia][ja];
}