Cod sursa(job #2784673)

Utilizator UnknownPercentageBuca Mihnea-Vicentiu UnknownPercentage Data 16 octombrie 2021 23:30:10
Problema Barbar Scor 10
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.3 kb
#include <bits/stdc++.h>

using namespace std;

inline void Open(const string Name) {
    #ifndef ONLINE_JUDGE
        (void)!freopen((Name + ".in").c_str(), "r", stdin);
        (void)!freopen((Name + ".out").c_str(), "w", stdout);
    #endif
}

int row[] = {-1, 1, 0, 0}, col[] = {0, 0, -1, 1};

vector <array <int, 2>> D;

char a[1001][1001], c[1001][1001];
char ch;

int N, M, xi, yi, xf, yf, ans;

bool valid(int i, int j) {
    return !(i <= 0 || i > N || j <= 0 || j > M);
}

bool Lee() {

    if(a[xi][yi] == '*')
        return 0;

    queue <array <int, 2>> q;
    q.push({xi, yi});

    c[xi][yi] = '*';

    while(!q.empty()) {
        int i = q.front()[0], j = q.front()[1];
        q.pop();

        for(int d = 0;d < 4;d++) {
            int ii = i + row[d], jj = j + col[d];
            if(ii == xf && jj == yf)
                return 1;

            if(c[ii][jj] == '.' && a[ii][jj] == '.') {
                c[ii][jj] = '*';
                q.push({ii, jj});
            }
        }
    }

    return 0;
}

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);

    Open("barbar");

    cin >> N >> M;
    for(int i = 1;i <= N;i++)
        for(int j = 1;j <= N;j++) {
            cin >> ch, a[i][j] = '.';
            if(ch == 'D') a[i][j] = '1', D.push_back({i, j});
            if(ch == 'I') xi = i, yi = j;
            if(ch == 'O') xf = i, yf = j;
            if(ch == '*') a[i][j] = '1';
        }

    for(int i = 1;i <= N;i++)
        c[i][M + 1] = c[i][0] = '*';

    for(int i = 1;i <= M;i++)
        c[0][i] = c[N + 1][i] = '*';

    int l = 1, r = N * M;
    while(l <= r) {
        int m = (l + r) / 2;

        for(int i = 1;i <= N;i++)
            for(int j = 1;j <= M;j++) {
                if(a[i][j] == '*') a[i][j] = '.';
                c[i][j] = '.';
            }

        for(auto &it : D) {
            int i = it[0], j = it[1];
            for(int k = 1;k < m;k++)
                for(int d = 0;d < 4;d++) {
                    if(valid(i + k * row[d], j + k * col[d])) a[i + k * row[d]][j + k * col[d]] = '*';
                }
        }

        if(!Lee()) {
            r = m - 1;
        } else {
            ans = m;
            l = m + 1;
        }
    }

    cout << ans;

    return 0;
}