Pagini recente » Cod sursa (job #2354698) | Cod sursa (job #2020459) | Monitorul de evaluare | Cod sursa (job #1607923) | Cod sursa (job #3316484)
#include <bits/stdc++.h>
#include <fstream>
using namespace std;
ifstream fin("barbar.in");
ofstream fout("barbar.out");
const int di[]={0,0,-1,1},dj[]={-1,1,0,0};
int n,m,a[1005][1005],h[1005][1005],si,sj,fi,fj,att;
bool gasit=false;
queue<pair<short,short>>q;
bool ok(int i,int j){
if(i<1||j<1||i>n||j>m) return false;
return true;
}
void lee(int att,int mij){
queue<pair<short,short>>q;
q.push({si,sj});
int i,j,ni,nj;
h[si][sj]=att;
if(a[si][sj]<mij||a[si][sj]==-1) return;
while(!q.empty()){
i=q.front().first;
j=q.front().second;
q.pop();
if(i==fi&&j==fj){
gasit=true;
return;
}
for(int k=0;k<4;k++){
ni=i+di[k];
nj=j+dj[k];
if(ok(ni,nj)){
if(a[ni][nj]!=-1&&a[ni][nj]>=mij&&h[ni][nj]!=att){
h[ni][nj]=att;
q.push({ni,nj});
}
}
}
}
if(h[fi][fj]==att) gasit=true;
}
int main(){
fin>>n>>m;
char c;
for(int i=1;i<=n;i++){
for(int j=1;j<=m;j++){
fin>>c;
if(c=='*'){
a[i][j]=-1;
}else if(c=='I'){
si=i;
sj=j;
}else if(c=='O'){
fi=i;
fj=j;
}else if(c=='D'){
q.push({i,j});
a[i][j]=-1;
}
}
}
int st=1,dr=-1,rez=-1;
while(!q.empty()){
int i,j,val,ni,nj;
i=q.front().first;
j=q.front().second;
q.pop();
val=a[i][j];
for(int k=0;k<4;k++){
ni=i+di[k];
nj=j+dj[k];
if(ok(ni,nj)){
if(a[ni][nj]==0){
if(val==-1) a[ni][nj]=1;
else a[ni][nj]=val+1;
dr=max(dr,a[ni][nj]);
q.push({ni,nj});
}
}
}
}
att=1;
while(st<=dr){
int mij=(st+dr)/2;
gasit=false;
lee(att,mij);
att++;
if(gasit){
st=mij+1;
if(rez==-1) rez=mij;
else rez=max(rez,mij);
}else{
dr=mij-1;
}
}
fout<<rez;
return 0;
}