Cod sursa(job #3299025)

Utilizator InformaticianInDevenire1Munteanu Mihnea Gabriel InformaticianInDevenire1 Data 3 iunie 2025 18:58:43
Problema Barbar Scor 30
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.75 kb
#include <bits/stdc++.h>
#define fi first
#define se second

using namespace std;

ifstream fin ("barbar.in");
ofstream fout ("barbar.out");

int n,m;
char ch[1005][1005];
int viz[1005][1005];
int Lee[1005][1005];
int dx[4],dy[4];
priority_queue <pair <int,pair <int,int>>> h; // value ; indexI indexJ

void MakeDs(){
    dx[1] = 0;
    dx[3] = 0;
    dx[0] = -1;
    dx[2] = 1;
    dy[0] = 0;
    dy[2] = 0;
    dy[1] = 1;
    dy[3] = -1;
    return;
}

bool IsInMatrix(int i,int j){
    if (i<1 or n<i) return 0;
    if (j<1 or m<j) return 0;
    return 1;
}

bool IsWalkable(int i,int j){
    if (ch[i][j]=='I' or ch[i][j]=='O' or ch[i][j]=='.') return 1;
    return 0;
}

void Lee_Function(int i1,int j1){
    for (int i=1;i<=n;++i){
        for (int j=1;j<=m;++j){
            viz[i][j] = 0;
        }
    }
    queue <pair <int,int>> q;
    q.push({i1,j1});
    viz[i1][j1] = 1;
    Lee[i1][j1] = 0;
    while (!q.empty()){
        int x = q.back().first, y = q.back().second;
        q.pop();
        for (int k=0;k<=3;++k){
            int nx = x+dx[k], ny = y+dy[k];
            if (IsInMatrix(nx,ny)==1 and IsWalkable(nx,ny)==1 and viz[nx][ny]==0){
                //if (Lee[nx][ny]==1e9) Lee[nx][ny] = Lee[x][y]+1;
                //else Lee[nx][ny] = min(Lee[x][y]+1,Lee[nx][ny]);
                Lee[nx][ny] = min(Lee[x][y]+1,Lee[nx][ny]);
                viz[nx][ny] = 1;
                q.push({nx,ny});
            }
        }
    }
    return;
}

int main()
{
    MakeDs();
    fin >> n >> m;
    int ist,jst;
    int ifn,jfn;
    for (int i=1;i<=n;++i){
        for (int j=1;j<=m;++j){
            fin >> ch[i][j];
            Lee[i][j] = 1e9;
            if (ch[i][j]=='I'){
                ist = i;
                jst = j;
            }
            if (ch[i][j]=='O'){
                ifn = i;
                jfn = j;
            }
        }
    }
    for (int i=1;i<=n;++i){
        for (int j=1;j<=m;++j){
            if (ch[i][j]=='D'){
                Lee_Function(i,j);
            }
        }
    }
    for (int i=1;i<=n;++i){
        for (int j=1;j<=m;++j){
            viz[i][j] = 0;
        }
    }
    h.push({Lee[ist][jst],{ist,jst}});
    viz[ist][jst] = 1;
    int ans = Lee[ist][jst];
    while (!h.empty() and !viz[ifn][jfn]){
        int x = h.top().se.fi, y = h.top().se.se;
        ans = min(ans,Lee[x][y]);
        h.pop();
        for (int k=0;k<=3;++k){
            int nx = x+dx[k], ny = y+dy[k];
            if (IsInMatrix(nx,ny) and IsWalkable(nx,ny)==1 and viz[nx][ny]==0){
                h.push({Lee[nx][ny],{nx,ny}});
                viz[nx][ny] = 1;
            }
        }
    }
    if (viz[ifn][jfn]==0) ans = -1;
    fout << ans;
    return 0;
}