Pagini recente » Cod sursa (job #2129386) | Cod sursa (job #1924439) | Cod sursa (job #2004256) | Cod sursa (job #2421518) | Cod sursa (job #611331)
Cod sursa(job #611331)
#include <iostream>
#include <queue>
#define NMax 1010
#define Inf 1000000000
using namespace std;
int N, M, Value[NMax][NMax], SX, SY, FX, FY, S=-1;
queue <int> QX, QY;
int XD[4]={-1, 0, 1, 0}, YD[4]={0, 1, 0, -1};
bool Vis[NMax][NMax];
void Read ()
{
freopen ("barbar.in", "r", stdin);
scanf ("%d %d\n", &N, &M);
for (int i=1; i<=N; ++i)
{
for (int j=1; j<=M; ++j)
{
char C;
scanf ("%c", &C);
if (C=='D')
{
Value[i][j]=1;
QX.push (i);
QY.push (j);
}
if (C=='*')
{
Value[i][j]=-1;
}
if (C=='I')
{
SX=i;
SY=j;
}
if (C=='O')
{
FX=i;
FY=j;
}
}
scanf ("\n");
}
for (int i=0; i<=N+1; ++i)
{
Value[i][0]=Value[i][M+1]=-1;
}
for (int j=0; j<=M+1; ++j)
{
Value[0][j]=Value[N+1][j]=-1;
}
}
void Print ()
{
freopen ("barbar.out", "w", stdout);
printf ("%d\n", S);
}
void BuildValue ()
{
while (!QX.empty ())
{
int X=QX.front (); QX.pop ();
int Y=QY.front (); QY.pop ();
for (int d=0; d<4; ++d)
{
int NewX=X+XD[d];
int NewY=Y+YD[d];
if (Value[NewX][NewY]==0)
{
Value[NewX][NewY]=Value[X][Y]+1;
QX.push (NewX);
QY.push (NewY);
}
}
}
}
bool Initialize (int DMax)
{
if (Value[SX][SY]<DMax)
{
return false;
}
for (int i=1; i<=N; ++i)
{
for (int j=1; j<=M; ++j)
{
Vis[i][j]=false;
}
}
while (!QX.empty ())
{
QX.pop ();
}
while (!QY.empty ())
{
QY.pop ();
}
Vis[SX][SY]=true;
QX.push (SX);
QY.push (SY);
return true;
}
bool Lee (int DMax)
{
if (!Initialize (DMax))
{
return false;
}
while (!QX.empty ())
{
int X=QX.front (); QX.pop ();
int Y=QY.front (); QY.pop ();
for (int d=0; d<4; ++d)
{
int NewX=X+XD[d];
int NewY=Y+YD[d];
if (Value[NewX][NewY]!=-1 and Value[NewX][NewY]>=DMax and !Vis[NewX][NewY])
{
Vis[NewX][NewY]=true;
QX.push (NewX);
QY.push (NewY);
if (Vis[FX][FY])
{
return true;
}
}
}
}
if (Vis[FX][FY])
{
return true;
}
return false;
}
int main()
{
Read ();
BuildValue ();
int L=1, R=Inf;
while (L<=R)
{
int Mid=(L+R)/2;
if (Lee (Mid))
{
S=Mid-1;
L=Mid+1;
}
else
{
R=Mid-1;
}
}
Print ();
return 0;
}