Cod sursa(job #2923388)

Utilizator vladsipunct5555Butnrau Vlad vladsipunct5555 Data 13 septembrie 2022 09:23:59
Problema Barbar Scor 90
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.42 kb
#include <fstream>
#include <queue>
#include <set>
using namespace std;
ifstream in ("barbar.in");
ofstream out ("barbar.out");
int n, m;
int a[1001][1001];
int startx, starty, endx, endy;
int dist[1001][1001];
int drx[] = {0, 1, 0, -1};
int dry[] = {1, 0, -1, 0};
bool isValid(int x, int y)
{
    if (x < 1 || x > n || y < 1 || y > m || a[x][y] == '*')
        return false;
    return true;
}
void dragoni (queue <pair <int, int> > q) {
    while (!q.empty())
    {
        auto front = q.front();
        q.pop();
        int x = front.first;
        int y = front.second;
        for (int i = 0; i <= 3;++i)
        {
            int newx = x + drx[i];
            int newy = y + dry[i];
            if (dist[newx][newy] == -1)
            {
                dist[newx][newy] = dist[x][y] + 1;
                q.push({newx, newy});
            }
        }
    }
}
int min1 (int a, int b)
{
    return a < b ? a : b;
}
int minim = 2000;
bool viz[1001][1001];
bool found = false;
void lee ()
{
    set <pair <int, pair <int, int> > > seti;
    seti.insert({-dist[startx][starty], {startx, starty}});
    while (!seti.empty())
    {
        auto front = *(seti.begin());
        seti.erase(seti.begin());
        int value = -front.first;
        int x = front.second.first;
        int y = front.second.second;
        if(viz[x][y] == 1)
            continue;
        minim = min1(minim, value);
        viz[x][y] = 1;
        if (x == endx && y == endy) {
            found = true;
            return;
        }
        for (int i = 0; i <= 3; ++i)
        {
            int newx = x + drx[i];
            int newy = y + dry[i];
            int value = -dist[newx][newy];
            if (isValid(newx, newy))
                seti.insert({value, {newx, newy}});
        }
    }
}
int main ()
{
    in >> n >> m;
    char c;
    for (int i = 1;i<=n;++i)
        for (int j = 1;j<=m;++j)
        {
            in >> c;
            a[i][j] = c;
            if (c == 'I')
                startx = i, starty = j;
            if (c == 'O')
                endx = i, endy = j;
        }
    queue <pair <int, int> > q;
    for (int i = 1;i<=n;++i)
        for (int j = 1;j<=m;++j)
            if (a[i][j] == 'D')
            {
                q.push({i, j});
                dist[i][j] = 0;
            }
            else
                dist[i][j] = -1;
    dragoni(q);
    lee();
    if (found == true)
        out << minim << '\n';
    else
        out << -1 << '\n';
    return 0;
}