Cod sursa(job #2552294)

Utilizator mariamirabella2Bucur-Sabau Maria-Mirabela mariamirabella2 Data 20 februarie 2020 19:04:07
Problema Barbar Scor 40
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.24 kb
#include <fstream>
#include <deque>

using namespace std;

ifstream cin("barbar.in");
ofstream cout("barbar.out");

int n,m,xs,ys,xf,yf,d[1005][1005];
string s[1005];
deque<int>ql,qc;
const int dx[]={-1,0,1,0},dy[]={0,-1,0,1};
short int a[1005][1005];

void Fill(int i,int j,int mij){
    int ii,jj;
    a[i][j]=1;
    for(int k=0;k<4;k++){
        ii=i+dx[k];
        jj=j+dy[k];
        if(ii>=0 && ii<n && jj>=0 && jj<m){
            if(!a[ii][jj] && d[ii][jj]>=mij && s[ii][jj]!='*' ){
                Fill(ii,jj,mij);
            }
        }
    }
}
int main()
{
    cin>>n>>m;
    for(int i=0;i<n;i++){
        for(int j=0;j<m;j++){
            d[i][j]=(1<<20);
        }
    }
    for(int i=0;i<n;i++){
        cin>>s[i];
        for(int j=0;j<m;j++){
            if(s[i][j]=='D'){
                ql.push_back(i);
                qc.push_back(j);
                d[i][j]=0;
            }
            if(s[i][j]=='I'){
                xs=i;
                ys=j;
            }
            if(s[i][j]=='O'){
                xf=i;
                yf=j;
            }
        }
    }
    int i,j,ii,jj;
    while(!ql.empty()){
        i=ql.front();
        j=qc.front();
        ql.pop_front();
        qc.pop_front();
        for(int k=0;k<4;k++){
            ii=i+dx[k];
            jj=j+dy[k];
            if(ii>=0 && ii<n && jj>=0 && jj<m ){
                if(d[ii][jj]>d[i][j]+1 && s[ii][jj]!='*'){
                    d[ii][jj]=d[i][j]+1;
                    ql.push_front(ii);
                    qc.push_front(jj);
                }
            }
        }
    }
 /*   for(int i=0;i<n;i++,cout<<'\n'){
        for(int j=0;j<m;j++,cout<<" "){
            cout<<d[i][j];
        }
    }
    */
    bool ok=false;
    int sol=0;
    int st=0,dr=n+m;
    while(st<dr){
        int mj=(st+dr)/2;
        for(int i=0;i<n;i++){
            for(int j=0;j<m;j++){
                a[i][j]=0;
            }
        }
        Fill(xs,ys,mj);
        if(a[xf][yf]==0) {
            dr=mj-1;
        }
        else{
            ok=true;
            st=mj+1;
            sol=mj;
        }
    }
    if(ok==false){
        cout<<-1;
        return 0;
    }

    cout<<sol;

    return 0;
}