Pagini recente » Cod sursa (job #311962) | Cod sursa (job #679569) | Cod sursa (job #298344) | Statistici Laura Caliman (laura.caliman) | Cod sursa (job #1290866)
#include <cstdio>
#include <queue>
using namespace std;
const int nmax = 1005;
int dx[]={-1, 0, 1, 0};
int dy[]={0, 1, 0, -1};
int mat[nmax][nmax], n, m, ix, ox, iy, oy, i, j;
bool ok[nmax][nmax], sol, gasit;
queue < pair<int,int> > q;
void lee_dragoni()
{
while(!q.empty())
{
int nx=q.front().first;
int ny=q.front().second;
q.pop();
for(i=0; i<4; i++)
{
int xx=nx+dx[i];
int yy=ny+dy[i];
if(xx<=n && xx>0 && yy<=m && yy>0 && !mat[xx][yy])
{
q.push(make_pair(xx,yy));
mat[xx][yy]=mat[nx][ny]+1;
}
}
}
}
bool lee_okay(int mid)
{
q.push(make_pair(ix,iy));
ok[ix][iy]=1;
while(!q.empty() && !gasit)
{
int nx=q.front().first;
int ny=q.front().second;
q.pop();
for(i=0; i<4; i++)
{
int xx=nx+dx[i];
int yy=ny+dy[i];
if(xx<=n && xx>0 && yy<=m && yy>0 && mat[xx][yy]>=mid && !ok[xx][yy])
{
q.push(make_pair(xx,yy));
ok[xx][yy]=1;
if(xx==ox && yy==oy) return 1;
}
}
}
return 0;
}
int main()
{
freopen("barbar.in", "r", stdin);
freopen("barbar.out", "w", stdout);
scanf("%d %d\n", &n, &m);
for(i=1; i<=n; i++, scanf("\n"))
for(j=1; j<=m; j++)
{
char ch;
scanf("%c", &ch);
if(ch=='*') mat[i][j]=-1;
else if(ch=='D')
{
q.push(make_pair(i,j));
mat[i][j]=1;
}
else if(ch=='I') ix=i, iy=j;
else if(ch=='O') ox=i, oy=j;
}
lee_dragoni();
int st=1, dr=n*m;
for(i=1; i<=n; i++)
for(j=1; j<=m; j++)
{
if(mat[i][j]!=-1) ok[i][j]=0;
else ok[i][j]=1;
}
while(st<=dr)
{
int mid=(st+dr)/2;
if(lee_okay(mid) && mat[ix][iy]>=mid)
{
st=mid+1;
sol=1;
}
else dr=mid-1;
}
if(sol) printf("%d\n", dr-1);
else printf("-1");
fclose(stdin);
fclose(stdout);
return 0;
}