Cod sursa(job #716993)

Utilizator ELHoriaHoria Cretescu ELHoria Data 19 martie 2012 14:50:11
Problema Barbar Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.86 kb
#include <fstream>
#include <queue>
#define PII pair<int,int>
#define x first
#define y second
#define MP make_pair

using namespace std;

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

const int INF = int(1e9) ,  NMAX = 1005 ,
dx[] = {0,1,-1,0} , dy[] = {-1,0,0,1};
int  dmax[NMAX][NMAX] , DD[NMAX][NMAX] , N , M;
char A[NMAX][NMAX];
PII start , stop , now , curr;
queue< PII > Q;

bool check(const PII &p)
{
	return (p.x >= 0 && p.y >=0 && p.x < N  && p.y < M && A[p.x][p.y] != '*');
}

void read_data()
{
	fin>>N>>M , fin.get();
	for(int i = 0;i < N;++i)
		fin.getline(A[i],NMAX);
	
	for(int i = 0;i < N;++i)
		for(int j = 0;j < M;++j) {
		DD[i][j] = INF;
		dmax[i][j] = -1;
			if(A[i][j] == 'I') start = MP(i,j);
		else
			if(A[i][j] == 'O') stop = MP(i,j);
		else
			if(A[i][j] == 'D') Q.push(MP(i,j)) , DD[i][j] = 0;
		}
}

void bf_dragoni()
{
	while(!Q.empty())
	{
		now = Q.front() , Q.pop();
		for(int k = 0;k < 4;++k)
		{
			curr = MP(now.x + dx[k],now.y + dy[k]);
			if(check(curr) == false) continue;
			if(DD[curr.x][curr.y] > DD[now.x][now.y] + 1)
				DD[curr.x][curr.y] = DD[now.x][now.y] + 1 , Q.push(curr);
		}
	}
}

void bf()
{
	A[stop.x][stop.y] = '.';
	dmax[start.x][start.y] = DD[start.x][start.y];
	for(Q.push(start);!Q.empty();)
	{
		now = Q.front() , Q.pop();
		for(int k = 0;k < 4;++k)
		{
			curr = MP(now.x + dx[k],now.y + dy[k]);
			if(check(curr) == false) continue;

			if(min(DD[curr.x][curr.y],dmax[now.x][now.y]) > dmax[curr.x][curr.y]) {
				dmax[curr.x][curr.y] = min(DD[curr.x][curr.y],dmax[now.x][now.y]);
				Q.push(curr);
				}
		}
	}
}

void write(int X[NMAX][NMAX])
{
	for(int i = 0;i < N;++i)
	{
		for(int j = 0;j < M;++j)
			fout<<X[i][j]<<" ";
	fout<<'\n';
	}
}

int main()
{
	read_data();
	bf_dragoni();
	bf();
	fout<<dmax[stop.x][stop.y];
	return 0;
}