Pagini recente » Cod sursa (job #543847) | Cod sursa (job #972918) | Cod sursa (job #827863) | Cod sursa (job #1795748) | Cod sursa (job #2297004)
//#include <iostream>
#include <queue>
#include <fstream>
#include <cstring>
using namespace std;
ifstream cin("barbar.in");
ofstream cout("barbar.out");
struct coord {
int x, y, cost;
};
queue <coord> q;
int l,c,begi,begj,endi,endj,b[1005][1005];
char a[1005][1005],v[1005][1005];
void lee()
{
coord w,w2;
int t;
int dx[]={-1,0,1,0};
int dy[]={0,1,0,-1};
while(q.empty()==false)
{
w=q.front();
q.pop();
for(t=0;t<4;t++)
{
w2.x=w.x+dx[t];
w2.y=w.y+dy[t];
w2.cost=w.cost+1;
if(a[w2.x][w2.y]!='*')
if(b[w2.x][w2.y]==0)
{
q.push(w2);
b[w2.x][w2.y]=w2.cost;
}
}
}
}
bool valid(int d)
{
if(b[begi][begj]<=d)
return false;
memset(v,'0',sizeof(v));
v[begi][begj]='1';
while(!q.empty())
q.pop();
coord aux,w;
int t;
int dx[]={-1,0,1,0};
int dy[]={0,1,0,-1};
w.x=begi;w.y=begj;
q.push(w);
while(!q.empty())
{
w=q.front();
q.pop();
for(t=0;t<4;t++)
{
aux.x=w.x+dx[t];
aux.y=w.y+dy[t];
if(a[aux.x][aux.y]!='*' and b[aux.x][aux.y]>d and v[aux.x][aux.y]!='1')
{
if(aux.x==endi and aux.y==endj)
return true;
v[aux.x][aux.y]='1';
q.push(aux);
}
}
}
return false;
}
int main()
{
int i,j,sol=-1,st,dr,d;
coord aux;
cin>>l>>c;
for(i=1;i<=l;i++)
cin>>a[i]+1;
for(i=0;i<=c+1;i++)
a[0][i]=a[l+1][i]='*';
for(i=0;i<=l+1;i++)
a[i][0]=a[i][c+1]='*';
for(i=1;i<=l;i++)
for(j=1;j<=c;j++)
if(a[i][j]=='I')
{
begi=i;begj=j;
}
else
if(a[i][j]=='O')
{
endi=i;endj=j;
}
else
if(a[i][j]=='D')
{
aux.x=i;
aux.y=j;
aux.cost=1;
q.push(aux);
b[i][j]=1;
}
lee();
st=0;dr=1000;
while(st<=dr)
{
d=(st+dr)>>1;
if(valid(d))
{
sol=d;
st=d+1;
}
else
dr=d-1;
}
cout<<sol<<"\n";
return 0;
}