Cod sursa(job #1252474)

Utilizator hrazvanHarsan Razvan hrazvan Data 30 octombrie 2014 19:51:08
Problema Barbar Scor 100
Compilator c Status done
Runda Arhiva de probleme Marime 2.29 kb
#include <stdio.h>
#define MAXNM 1000
char trecut[MAXNM + 1][MAXNM + 1];
char ma[MAXNM + 1][MAXNM + 1];
short coadal[MAXNM * MAXNM + 1], coadac[MAXNM * MAXNM + 1], dist[MAXNM + 1][MAXNM + 1];
int d[4][2] = {{1, 0}, {0, -1}, {-1, 0}, {0, 1}};
int gasit, li, ci, le, ce;

int min2(int a, int b){
  return a < b ? a : b;
}

void bfs(int st, int dr, char tip, int k, int n, int m){
  int i, x, y;
  if(dist[li][ci] < k)  return 0;
  while(st < dr){
    for(i = 0; i < 4; i++){
      x = coadal[st] + d[i][0];
      y = coadac[st] + d[i][1];
      if(x > 0 && x <= n && y > 0 && y <= m && !trecut[x][y] && ma[x][y] == 0){
        trecut[x][y] = 1;
        if(tip == 0){
          coadal[dr] = x;
          coadac[dr] = y;
          dist[x][y] = dist[coadal[st]][coadac[st]] + 1;
          dr++;
        }
        else if(dist[x][y] >= k){
          coadal[dr] = x;
          coadac[dr] = y;
          if(x == le && y == ce){
            gasit = 1;
          }
          dr++;
        }
      }
    }
    st++;
  }
}

char bun(int k, int n, int m){
  gasit = 0;
  coadal[1] = li;
  coadac[1] = ci;
  int i, j;
  for(i = 0; i <= MAXNM; i++){
    for(j = 0; j <= MAXNM; j++){
      trecut[i][j] = 0;
    }
  }
  bfs(1, 2, 1, k, n, m);
  return gasit == 0 ? 0 : 1;
}

int caut(int n, int m){
  int pas = 1 << 9, i = 0;
  while(pas > 0){
    if(bun(i + pas, n, m))
      i += pas;
    pas >>= 1;
  }
  if(!bun(0, n, m))  return -1;
  return i;
}

int main(){
  FILE *in = fopen("barbar.in", "r");
  int n, m, i, j, dr = 1;
  fscanf(in, "%d%d ", &n, &m);
  char ch;
  for(i = 1; i <= n; i++){
    for(j = 1; j <= m; j++){
      ch = fgetc(in);
      switch(ch){
        case 'D':
          coadal[dr] = i;
          coadac[dr] = j;
          trecut[i][j] = 1;
          dr++;
          break;
        case 'I':
          li = i;
          ci = j;
          break;
        case '*':
          ma[i][j] = 1;
          break;
        case 'O':
          le = i;
          ce = j;
          break;
        case '.':
          ma[i][j] = 0;
          break;
      }
    }
    fgetc(in);
  }
  fclose(in);
  bfs(1, dr, 0, 0, n, m);
  int rez = caut(n, m);
  FILE *out = fopen("barbar.out", "w");
  fprintf(out, "%d", rez);
  fclose(out);
  return 0;
}