Cod sursa(job #2958559)

Utilizator LukyenDracea Lucian Lukyen Data 26 decembrie 2022 23:07:10
Problema Barbar Scor 50
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.16 kb
#include <fstream>
#include <queue>
#include <climits>
#include <cstring>
using namespace std;

ifstream fin("barbar.in");
ofstream fout("barbar.out");
const short vec_len = 1005;

struct pos
{
  short l;
  short c;
};

short n, m;
short dmap[vec_len][vec_len];
short dirl[] = {-1, 0, 1, 0}, dirc[] = {0, 1, 0, -1};

pos tstart, texit;
queue<pos> drag;
queue<pos> path;

bool check(short l, short c)
{
  if (l < 1 || l > n)
    return false;

  if (c < 1 || c > m)
    return false;

  if (dmap[l][c] == -1)
    return false;

  return true;
}

void dragLee()
{
  bool vis[vec_len][vec_len] = {false};
  while (!drag.empty())
  {
    pos curr = drag.front();
    drag.pop();

    short nl = curr.l, nc = curr.c;
    for (short i = 0; i < 4; i++)
    {
      nl = curr.l + dirl[i];
      nc = curr.c + dirc[i];

      if (check(nl, nc) && !vis[nl][nc])
      {
        dmap[nl][nc] = dmap[curr.l][curr.c] + 1;
        vis[curr.l][curr.c] = true;
        drag.push(pos{nl, nc});
      }
    }
  }
}

short res[vec_len][vec_len];
void pathLee()
{
  path.push(pos{tstart.l, tstart.c});
  res[tstart.l][tstart.c] = dmap[tstart.l][tstart.c];
  while (!path.empty())
  {
    pos curr = path.front();
    path.pop();

    short nl, nc;
    for (short i = 0; i < 4; i++)
    {
      nl = curr.l + dirl[i];
      nc = curr.c + dirc[i];

      if (check(nl, nc) && res[nl][nc] < min(res[curr.l][curr.c], dmap[nl][nc]))
      {
        res[nl][nc] = min(res[curr.l][curr.c], dmap[nl][nc]);
        path.push(pos{nl, nc});
      }
    }
  }

  if (res[texit.l][texit.c] == 0)
    fout << "-1";
  else
    fout << res[texit.l][texit.c];
}

int main()
{
  fin.tie(NULL);
  fout.tie(NULL);
  ios::sync_with_stdio(false);

  fin >> n >> m;

  char x;
  for (short i = 1; i <= n; i++)
    for (short j = 1; j <= m; j++)
    {
      fin >> x;
      if (x == 'D')
        drag.push(pos{i, j}), dmap[i][j] = 0;
      else if (x == 'I')
        tstart = pos{i, j};
      else if (x == '*')
        dmap[i][j] = -1;
      else if (x == 'O')
        texit = pos{i, j};
    }

  dragLee();
  pathLee();

  return 0;
}