Cod sursa(job #3342385)

Utilizator amalia_ghicaAmalia Ghica amalia_ghica Data 23 februarie 2026 23:17:29
Problema Barbar Scor 80
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.2 kb
#include <bits/stdc++.h>

using namespace std;
int mat[1005][1005], dr[1005][1005], viz[1005][1005];
queue <pair<int, int>> q;
priority_queue<tuple<int, int, int>> pq;
int dlin[] = {0, -1, 0, 1};
int dcol[] = {-1, 0, 1, 0};
int main()
{
    ifstream cin("barbar.in");
    ofstream cout("barbar.out");
    int n, m;
    cin >> n >> m;
    string s;
    for(int i = 1; i <= n; i++){
        cin >> s;
        for(int j = 0; j < m; j++){
            dr[i][j + 1] = -1;
            if(s[j] == 'D'){
                dr[i][j + 1] = 0;
                mat[i][j + 1] = 1;
                q.push({i, j + 1});
            }else if(s[j] == 'I'){
                mat[i][j + 1] = 2;
                pq.push({1000000, i, j + 1});
            }else if(s[j] == 'O'){
                mat[i][j + 1] = 3;
            }else if(s[j] == '*')
                mat[i][j + 1] = -1;
        }
    }
    for(int i = 0; i <= n; i++){
        mat[i][0] = mat[i][m + 1] = -2;
        dr[i][0] = dr[i][m + 1] = -2;
    }
    for(int i = 0; i <= m; i++){
        dr[0][i] = dr[n + 1][i] = -2;
        mat[0][i] = mat[n + 1][i] = -2;
    }
    int l, c, xl, xc;
    while(!q.empty()){
        l = q.front().first;
        c = q.front().second;
        q.pop();
        for(int i = 0; i < 4; i++){
            xl = l + dlin[i];
            xc = c + dcol[i];
            if(dr[xl][xc] == -1){
                dr[xl][xc] = dr[l][c] + 1;
                q.push({xl, xc});
            }
        }
    }
    int d, mn = 1000000, ok = 0;
    while(!pq.empty()){
        d = get<0>(pq.top());
        l = get<1>(pq.top());
        c = get<2>(pq.top());
        pq.pop();
        mn = min(mn, d);
        viz[l][c] = 1;
        if(mat[l][c] == 3){
            ok = 1;
            break;
        }
        for(int i = 0; i < 4; i++){
            xl = l + dlin[i];
            xc = c + dcol[i];
            if(viz[xl][xc] == 0){
                if(mat[xl][xc] == 0 || mat[xl][xc] >= 2){
                    pq.push({dr[xl][xc], xl, xc});
                    viz[xl][xc] = 1;
                }
            }
        }
    }
    if(ok == 0){
        cout << "-1";
    }else{
        cout << mn;
    }
    return 0;
}