Cod sursa(job #2646731)

Utilizator DenisONIcBanu Denis Andrei DenisONIc Data 1 septembrie 2020 19:59:54
Problema Barbar Scor 30
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.2 kb
#include <bits/stdc++.h>
using namespace std;

#define NMAX 1005

int n,m,mat2[NMAX][NMAX], uz[NMAX][NMAX];
char mat[NMAX][NMAX];

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

void fillD(int x,int y, int d){
    mat2[x][y] = 1;
    if (d == 0)
        return;

    for (int i=1;i<=n;i++)
        for (int j=1;j<=m;j++)
            for (int k=0;k<4;k++){
                int X,Y;
                X = x + dx[k];
                Y = y + dy[k];
                if (X <= 0 || X > n || Y <= 0 || Y > m) continue;
                if (mat2[X][Y] == 1) continue;
                fillD(X,Y,d-1);
            }
}

vector<pair<int, int>> Q;

int OK(int x){
    for (int i=1;i<=n;i++) for (int j=1;j<=m;j++){
        mat2[i][j] = 0;
        uz[i][j] = 1e9;
        if (mat[i][j] == '*')
            mat2[i][j] = 1;
    }

    int sx,sy,fx,fy;
    for (int i=1;i<=n;i++){
        for (int j=1;j<=m;j++){
            if (mat[i][j] == 'I'){
                sx = i;
                sy = j;
            }
            if (mat[i][j] == 'O'){
                fx = i;
                fy = j;
            }
            if (mat[i][j] == 'D'){
                fillD(i,j,x);
            }
        }
    }

    Q.clear();
    Q.push_back({sx,sy});
    uz[sx][sy] = 0;
    for (int i=0;i<Q.size();i++){
        pair<int, int> crt = Q[i];
        for (int k=0;k<4;k++){


            int X = crt.first + dx[k];
            int Y = crt.second + dy[k];
            if (X <= 0 || X > n || Y <= 0 || Y > m) continue;
            if (mat2[X][Y] == 1) continue;
            if (uz[X][Y] != 1000000000) continue;
            uz[X][Y] = uz[crt.first][crt.second] + 1;
            Q.push_back({X,Y});
        }
    }

    return uz[fx][fy] != 1000000000;
}

int main()
{
    freopen("barbar.in","r",stdin);
    freopen("barbar.out","w",stdout);

    cin >> n >> m;
    for (int i=1;i<=n;i++){
        cin >> mat[i] + 1;
    }

    int st = 0, p = 1;
    for (;p<=min(n,m);p<<=1);
    for (;p>=1;p>>=1){
        if(st + p < min(n,m) && OK(st + p))
            st += p;
    }

    if (!OK(st)){
        cout << -1 << '\n';
    }
    else{
        cout << st+1 << '\n';
    }
    return 0;
}