Pagini recente » Cod sursa (job #604451) | Borderou de evaluare (job #600229) | Cod sursa (job #26596) | Cod sursa (job #1072575) | Cod sursa (job #2641455)
#include <iostream>
#include <fstream>
#include <queue>
using namespace std;
ifstream in("barbar.in");
ofstream out("barbar.out");
int matrice[1002][1002],cm[1002][1002];
queue<pair<int,int>>q;
int main()
{
int m,n,li,ci,lf,cf;
pair<int,int> nod;
in>>m>>n;
in.get();
for(int i=1;i<=m;i++)
{
for(int j=1;j<=n;j++)
{
char c;
c=in.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.first=i;
nod.second=j;
q.push(nod);
}
}
in.get();
}
while(q.size()!=0)
{
int l=q.front().first,c=q.front().second;
if(l-1>0 && matrice[l-1][c]==0)
{
matrice[l-1][c]=matrice[l][c]+1;
nod.first=l-1;
nod.second=c;
q.push(nod);
}
if(c-1>0&&matrice[l][c-1]==0)
{
matrice[l][c-1]=matrice[l][c]+1;
nod.first=l;
nod.second=c-1;
q.push(nod);
}
if(l+1<=m&&matrice[l+1][c]==0)
{
matrice[l+1][c]=matrice[l][c]+1;
nod.first=l+1;
nod.second=c;
q.push(nod);
}
if(c+1<=n&&matrice[l][c+1]==0)
{
matrice[l][c+1]=matrice[l][c]+1;
nod.first=l;
nod.second=c+1;
q.push(nod);
}
q.pop();
}
int st=0,dr=1000,mij,p=-1;
while(st<=dr)
{
mij=(dr+st)/2;
nod.first=li;
nod.second=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().first,c=q.front().second;
if(l-1>0&&cm[l-1][c]>mij)
{
cm[l-1][c]=0;
nod.first=l-1;
nod.second=c;
q.push(nod);
}
if(c-1>0&&cm[l][c-1]>mij)
{
cm[l][c-1]=0;
nod.first=l;
nod.second=c-1;
q.push(nod);
}
if(l+1<=m&&cm[l+1][c]>mij)
{
cm[l+1][c]=0;
nod.first=l+1;
nod.second=c;
q.push(nod);
}
if(c+1<=n&&cm[l][c+1]>mij)
{
cm[l][c+1]=0;
nod.first=l;
nod.second=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;
}
}
out<<p;
return 0;
}