Cod sursa(job #2260922)

Utilizator AlexandruLuchianov1Alex Luchianov AlexandruLuchianov1 Data 15 octombrie 2018 19:13:25
Problema Barbar Scor 80
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.46 kb
#include <iostream>
#include <fstream>
#include <queue>

using namespace std;

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

int const nmax = 1000;
char v[1 + nmax][1 + nmax];
int dist[1 + nmax][1 + nmax];
int path[1 + nmax][1 + nmax];
int n ,m;
struct Square{
  int x;
  int y;
};
int const iplus[4] = {1 , -1 ,0 ,0};
int const jplus[4] = {0 ,0 ,-1 ,1};

bool valid(int x ,int y){
  return (1 <= x && x <= n) && (1 <= y && y <= m);
}

void flood(){///for dragons
  queue <Square> q;
  for(int i = 1 ; i <= n ;i++){
    for(int j = 1 ; j <= m ;j++){
      if(v[i][j] == 'D'){
        q.push({i , j});
        dist[i][j] = 0;
      }
    }
  }
  while(0 < q.size()){
    int x = q.front().x;
    int y = q.front().y;
    q.pop();
    for(int h = 0 ; h < 4 ;h++){
      int newx = x + iplus[h];
      int newy = y + jplus[h];
      if(valid(newx , newy) && (dist[newx][newy] == -1 || dist[x][y] + 1 < dist[newx][newy])){
        dist[newx][newy] = dist[x][y] + 1;
        q.push({newx , newy});
      }
    }
  }
}

int toact[5 + nmax][5 + nmax];

void computepath(int x , int y){
  queue <Square> q;
  q.push({x , y});
  path[x][y] = dist[x][y];
  while(0 < q.size()){
    x = q.front().x;
    y = q.front().y;

    q.pop();
    if(toact[x][y] == 1)
      continue;
    else
      toact[x][y] = 1;

    for(int h = 0 ; h < 4 ;h++){
      int newx = x + iplus[h];
      int newy = y + jplus[h];

      if(v[newx][newy] != '*' && v[newx][newy] != 'D' && valid(newx , newy)){
        int val;
        if(path[x][y] < dist[newx][newy]){
          val = path[x][y];
        } else
          val = dist[newx][newy];

        if(path[newx][newy] == -1 || path[newx][newy] < val){
          path[newx][newy] = val;
          q.push({newx , newy});
          toact[newx][newy] = 0;
        }

      }
    }
  }
}

int main()
{
  in >> n >> m;
  for(int i = 1 ; i <= n ; i++)
    in >> (v[i] + 1);

  for(int i = 1 ; i <= n ;i++){
    for(int j = 1 ; j <= m ;j++){
      dist[i][j] = -1;
      path[i][j] = -1;
    }
  }
  int startx , starty;
  int stopx , stopy ;

  for(int i = 1 ; i <= n ;i++){
    for(int j = 1 ; j <= m ;j++){
      in>>v[i][j];
      if(v[i][j] == 'I'){
        startx = i;
        starty = j;
      }

      if(v[i][j] == 'O'){
        stopx = i;
        stopy = j;
      }
    }
  }
  flood();
  computepath(startx , starty);

  out << path[stopx][stopy];

  return 0;
}