Pagini recente » Cod sursa (job #1852162) | Cod sursa (job #2857455) | Cod sursa (job #2298534) | Cod sursa (job #105235) | Cod sursa (job #1535885)
#include <fstream>
#include <algorithm>
#include <queue>
#include <cstring>
#define nmax 1010
using namespace std;
ifstream in("barbar.in");
ofstream out("barbar.out");
int N,M;
int A[nmax][nmax],D[nmax][nmax],VIZ[nmax][nmax];
int dl[]= {0,1,0,-1};
int dc[]= {-1,0,1,0};
struct nod
{
int x,y;
} start, stop, temp, nou;
queue <nod> q;
bool traseu(int p)
{
if(D[start.x][start.y]<p) return 0;
q.push(start);
memset(VIZ,0,sizeof(VIZ));
VIZ[start.x][start.y]=1;
while(!q.empty())
{
temp=q.front();
q.pop();
for(int lin,col,k=0; k<4; ++k)
{
lin =temp.x+dl[k];
col =temp.y+dc[k];
if(D[lin][col]>=p && !VIZ[lin][col])
{
VIZ[lin][col]=1;
nou.x=lin;
nou.y=col;
q.push(nou);
}
}
}
return VIZ[stop.x][stop.y];
}
void init()
{
for(int i=1; i<=N; ++i)
for(int j=1; j<=M; ++j)
D[i][j]=-2;
}
void bordare()
{
for(int i=0; i<=N+1; ++i) D[i][0]=D[i][M+1]=-1;
for(int i=0; i<=M+1; ++i) D[0][i]=D[N+1][i]=-1;
}
void citire()
{
char ch;
in>>N>>M;
init();
bordare();
for(int i=1; i<=N; ++i)
for(int j=1; j<=M; ++j)
{
in>>ch;
switch(ch)
{
case '*' :
D[i][j]=-1;
break;
case 'O' :
stop.x=i;
stop.y=j;
break;
case 'I' :
start.x=i;
start.y=j;
break;
case 'D' :
D[i][j]=0;
nou.x=i;
nou.y=j;
q.push(nou);
break;
}
}
}
void LEE()
{
while(!q.empty())
{
temp=q.front();
q.pop();
for(int lin,col,k=0; k<4; ++k)
{
lin=temp.x+dl[k];
col=temp.y+dc[k];
if(D[lin][col]==-2)
{
D[lin][col]=D[temp.x][temp.y]+1;
nou.x=lin;
nou.y=col;
q.push(nou);
}
}
}
}
void caut_bin(int &dist)
{
if(D[start.x][start.y] !=-2)
{
int st=0, dr=N*M, mij;
while(st<=dr)
{
mij=(st+dr)>>1;
if(traseu(mij))
{
dist=mij;
st=mij+1;
}
else dr=mij-1;
}
}
}
int main()
{
citire();
LEE(); //Lee plecand de la dragoni
int dist=-1;
caut_bin(dist);
out<<dist<<'\n';
return 0;
}