Cod sursa(job #3339381)

Utilizator Alexutu008Ionita Alexandru-Dumitru Alexutu008 Data 7 februarie 2026 17:44:20
Problema Barbar Scor 90
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.54 kb
#include<bits/stdc++.h>

using namespace std;

int dx[4] ={-1, 1, 0, 0}, dy[4] = {0, 0, -1, 1};
const int maxN=1e3+5;
int a[maxN][maxN], d[maxN][maxN];
int starti, startj, endi, endj;
int n, m; char c;
queue<pair<int, int>> q;

bool bfs(int value){
    for(int i=1;i<=n;++i) for(int j=1;j<=m;++j) if(a[i][j]!=-1) a[i][j]=INT_MAX;
    if (d[starti][startj]<value) return 0;
    q.push({starti, startj});
    a[starti][startj]=0;
    while(!q.empty()){
        int x = q.front().first, y=q.front().second;
        q.pop();
        for(int i=0;i<4;++i){
            int newx=x+dx[i], newy=y+dy[i];
            if(1<=newx && newx<=n && 1<=newy && newy<=m){
                if(a[newx][newy]!=-1 && a[newx][newy]>a[x][y]+1 && d[newx][newy]>=value){
                    a[newx][newy] = a[x][y] + 1;
                    q.push({newx, newy});
                }
            }
        }
    }
    if(a[endi][endj]!=INT_MAX)
        return 1;
    return 0;

}

int main(){
    ios::sync_with_stdio(0); cin.tie(0);
    freopen("barbar.in", "r", stdin);
    freopen("barbar.out", "w", stdout);

    for(int i=1;i<=maxN;i++)
        for(int j=1;j<=maxN;j++)
            d[i][j] = INT_MAX;


    cin>>n>>m;
    for(int i=1;i<=n;++i){
        for(int j=1;j<=m;++j){
            cin>>c;
            if(c=='I'){
                starti=i; startj=j;
            }
            else if(c=='D'){
                d[i][j]=1;
                // a[i][j]=-1;
                q.push({i, j});
            }
            else if(c=='O'){
                endi=i; endj=j;
            } 
            else if(c=='*'){
                a[i][j]=-1;
            }
        }
    }
    
    while (!q.empty())
    {
        int x = q.front().first, y = q.front().second;
        q.pop();
        for(int i=0;i<4;++i){
            int newx = x+dx[i], newy = y+dy[i];
            if(1<=newx && newx<=n && 1<=newy && newy<=m)
                if(d[newx][newy]>d[x][y]+1){
                    d[newx][newy] = d[x][y]+1;
                    q.push({newx, newy});
                }
        }
    }

    // for(int i=1;i<=n;++i){
    //     cout<<'\n';
    //     for(int j=1;j<=m;++j){
    //         cout<<d[i][j]<<' ';
    //     }
    // }
    
    int st=1, dr=1e6+1, poz=-1;
    while(st<=dr){
        // cout<<st<<' '<<dr<<'\n';
        int mid=st+dr>>1;
        if(bfs(mid)){
            st=mid+1;
            poz=mid;
        }
        else{
            dr=mid-1;
        }
    }
    if(poz!=-1)
        cout<<poz-1;
    else cout<<-1;
}