Pagini recente » Cod sursa (job #2418344) | Cod sursa (job #850144) | Cod sursa (job #2815845) | Cod sursa (job #243818) | Cod sursa (job #2631794)
#include <iostream>
#include <fstream>
#include <queue>
using namespace std;
ifstream r("barbar.in");
ofstream w("barbar.out");
int matrice[1002][1002], cm[1002][1002];
struct qu
{
int x, y;
};
queue<qu>q;
int main()
{
int m, n, li, ci, lf, cf;
qu nod;
r>>m>>n;
r.get();
for(int i=1; i<=m; i++)
{
for(int j=1; j<=n; j++)
{
char c;
c=r.get();
if(c=='*')
{
matrice[i][j]=-2;
}
if(c=='I')
{
li=i;
ci=j;
}
if(c=='O')
{
lf=i;
cf=j;
}
if(c=='D')
{
matrice[i][j]=1;
nod.x=i;
nod.y=j;
q.push(nod);
}
}
r.get();
}
while(q.size()!=0)
{
int l=q.front().x, c=q.front().y;
if(l-1>0 && matrice[l-1][c]==0)
{
matrice[l-1][c]=matrice[l][c]+1;
nod.x=l-1;
nod.y=c;
q.push(nod);
}
if(c-1>0 && matrice[l][c-1]==0)
{
matrice[l][c-1]=matrice[l][c]+1;
nod.x=l;
nod.y=c-1;
q.push(nod);
}
if(l+1<=m && matrice[l+1][c]==0)
{
matrice[l+1][c]=matrice[l][c]+1;
nod.x=l+1;
nod.y=c;
q.push(nod);
}
if(c+1<=n && matrice[l][c+1]==0)
{
matrice[l][c+1]=matrice[l][c]+1;
nod.x=l;
nod.y=c+1;
q.push(nod);
}
q.pop();
}
int st=0, dr=1000, mij, p=-1;
while(st<=dr)
{
mij=(dr+st)/2;
nod.x=li;
nod.y=ci;
q.push(nod);
for(int i=1;i<=m;i++){
for(int j=1;j<=n;j++){
cm[i][j]=matrice[i][j];
}
}
while(q.size()!=0)
{
int l=q.front().x, c=q.front().y;
if(l-1>0 && cm[l-1][c]>mij)
{
cm[l-1][c]=0;
nod.x=l-1;
nod.y=c;
q.push(nod);
}
if(c-1>0 && cm[l][c-1]>mij)
{
cm[l][c-1]=0;
nod.x=l;
nod.y=c-1;
q.push(nod);
}
if(l+1<=m && cm[l+1][c]>mij)
{
cm[l+1][c]=0;
nod.x=l+1;
nod.y=c;
q.push(nod);
}
if(c+1<=n && cm[l][c+1]>mij)
{
cm[l][c+1]=0;
nod.x=l;
nod.y=c+1;
q.push(nod);
}
q.pop();
}
if(cm[lf][cf]==0 && matrice[li][ci]>mij){
st=mij+1;
p=mij;
}
else{
dr=mij-1;
}
}
w<<p;
return 0;
}