Cod sursa(job #3342593)

Utilizator rayenn3D Andra rayenn3 Data 24 februarie 2026 20:51:25
Problema Barbar Scor 40
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.68 kb
#include <fstream>
#include <queue>
#define NMAX 1000

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

struct punct{
    int x, y;
};
queue <punct> q;

int a[NMAX + 2][NMAX + 2];
int dist[NMAX + 2][NMAX + 2];
int viz[NMAX + 2][NMAX + 2];

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

int bfs(){
    int rez = -1;
    punct aux, nou;
    while(!q.empty()){
        aux = q.front();
        for(int dir = 0; dir < 4; dir++){
            nou.x = aux.x + dx[dir];
            nou.y = aux.y + dy[dir];
            if(a[nou.x][nou.y] == 0 && viz[nou.x][nou.y] != 1){
                dist[nou.x][nou.y] = dist[aux.x][aux.y] + 1;
                viz[nou.x][nou.y] = 1;
                q.push(nou);
            }
            if(a[nou.x][nou.y] == 2){
                if(rez == -1 || rez > dist[aux.x][aux.y])
                    rez = dist[aux.x][aux.y];
            }
        }
        q.pop();
    }
    return rez;
}
int main()
{
    int n, m, st, dr, mij, cnt, last;
    char x;
    bool ok;
    punct aux, nou, barbar, dragon;
    fin >> n >> m;
    cnt = 0;
    for(int i = 1; i <= n; i++)
        for(int j = 1; j <= m; j++){
            fin >> x;
            if(x == 'D'){
                a[i][j] = 1;
                dragon.x = i;
                dragon.y = j;
                q.push(dragon);
            }
            else if(x == '*')
                a[i][j] = -2;
            else if(x == 'I')
                a[i][j] = 2;
        }
     for(int i = 1; i <= n; i++)
        a[i][0] = a[i][m + 1] = -2;
    for(int j = 1; j <= m; j++)
        a[0][j] = a[n + 1][j] = -2;

    fout << bfs();
    return 0;
}