Cod sursa(job #184839)

Utilizator AndreyPAndrei Poenaru AndreyP Data 24 aprilie 2008 13:12:10
Problema Barbar Scor 30
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.36 kb
#include<stdio.h>
int a[15][15],b[15][15],r,c;
char ok;
const char dx[]={0,1,0,-1};
const char dy[]={1,0,-1,0};
struct cod
{
	int y,x;
};
int inc,sf=-1;
cod k1,k2,now,next,co[1000];
void citeste()
{
	int i,j;
	char aux;
	for(i=0; i<=r+1; i++)
		a[i][0]=a[i][c+1]=-2;
	for(i=0; i<=c+1; i++)
		a[0][i]=a[r+1][i]=-2;
	for(i=1; i<=r; i++)
	{
		for(j=1; j<=c; j++)
		{
			scanf("%c",&aux);
			switch(aux)
			{
				case 'D': {co[++sf].x=j; co[sf].y=i; a[i][j]=-1;} break;
				case '.': break;
				case '*': a[i][j]=-2; break;
				case 'I': {k1.x=j; k1.y=i;} break;
				case 'O': {k2.x=j; k2.y=i;} break;
			}
		}
		scanf("\n");
	}
}
void bf()
{
	int i;
	while(inc<=sf)
	{
		now=co[inc++];
		for(i=0; i<4; i++)
		{
			next.x=now.x+dx[i];
			next.y=now.y+dy[i];
			if(a[next.y][next.x]==0)
			{
				co[++sf]=next;
				if(a[now.y][now.x]!=-1)
					a[next.y][next.x]=a[now.y][now.x]+1;
				else
					a[next.y][next.x]=1;
			}
		}
	}
}
/*void dfs(int x,int y)
{
	int i,x1,y1;
	for(i=0; i<4; i++)
	{
		x1=x+dx[i];
		y1=y+dy[i];
		if(a[y1][x1]!=-2)
		{
			int min=a[y1][x1];
			if(b[y][x]<min)
				min=b[y][x];
			if(min>b[y1][x1])
			{
				b[y1][x1]=min;
				if((y1==k2.y)&&(x1==k2.x))
					ok=1;
				dfs(x1,y1);
			}
		}
	}
}*/
int m,rez=-1;
int bf1()
{
	inc=0;
	sf=0;
	int i,j;
	if(a[k1.y][k1.x]>=m)
		co[0]=k1;
	else
		return 0;
	for(i=1; i<=r; i++)
	{
		for(j=1; j<=c; j++)
			b[i][j]=0;
	}
	b[k1.y][k1.x]=1;
	while((inc<=sf)&&(!b[k2.y][k2.x]))
	{
		now=co[inc++];
		for(i=0; i<4; i++)
		{
			next.y=now.y+dy[i];
			next.x=now.x+dx[i];
			if((!b[next.y][next.x])&&(a[next.y][next.x]>=m)&&(a[next.y][next.x]!=-2))
			{
				co[++sf]=next;
				b[next.y][next.x]=1;
			}
		}
	}
	if(b[k2.y][k2.x])
		return 1;
	return 0;
}
void caut()
{
	int st=0,dr=2100000;
	int ok;
	while(st<dr)
	{
		m=(st+dr)/2;
		ok=bf1();
		//printf("%d ",ok);
		if(ok)
		{
			rez=m;
			st=m+1;
		}
		else
			dr=m;
	}
	//printf("\n\n");
}
int main()
{
	freopen("barbar.in","r",stdin);
	freopen("barbar.out","w",stdout);
	scanf("%d%d\n",&r,&c);
	citeste();
	bf();
	for(int i=1; i<=r; i++)
	{
		for(int j=1; j<=c; j++)
			if(a[i][j]==-1)
				a[i][j]=0;
	}
	//b[k1.y][k1.x]=a[k1.y][k1.x];
	//dfs(k1.x,k1.y);
	caut();
	if(rez!=-1)
		printf("%d\n",rez);
	else
		printf("-1\n");
	/*for(int i=0; i<=r+1; i++)
	{
		for(int j=0; j<=c+1; j++)
			printf("%2d ",a[i][j]);
		printf("\n");
	}*/
	return 0;
}