Pagini recente » Borderou de evaluare (job #2093452) | Cod sursa (job #3274246) | Borderou de evaluare (job #2411959) | Borderou de evaluare (job #1826660) | Cod sursa (job #3323246)
#include <bits/stdc++.h>
using namespace std;
ifstream fin("barbar.in");
ofstream fout("barbar.out");
int r, c, m[1002][1002], is, js, ir, jr, rez;
int dx[4]={0,1,0,-1}, dy[4]={-1,0,1,0};
char a;
void bordare(){
for(int i=0;i<=r+1;i++)
m[i][0]=m[i][c+1]=1;
for(int j=1;j<=c;j++)
m[0][j]=m[r+1][j]=1;
}
int main(){
ios_base::sync_with_stdio(0);
fin.tie(NULL);
fout.tie(NULL);
fin>>r>>c;
vector <pair <int, int>> dr;
for(int i=1;i<=r;i++){
for(int j=1;j<=c;j++){
fin>>a;
if(a=='.')
m[i][j]=0;
if(a=='*')
m[i][j]=1;
if(a=='I'){
m[i][j]=0;
is=i;
js=j;
}
if(a=='D'){
m[i][j]=1;
dr.push_back({i,j});
}
if(a=='O'){
m[i][j]=0;
ir=i;
jr=j;
}
}
}
bordare();
/*for(int i=0;i<=r+1;i++){
for(int j=0;j<=c+1;j++)
cout<<m[i][j]<<' ';
cout<<endl;
}*/
int s=1, d=min(r,c)-1;
while(s<d){
int mij=(s+d)/2;
queue <pair <int,pair <int,int>>> q;
bitset <1003> viz[r+2];
for(auto dg : dr)
q.push({1,{dg.first,dg.second}});
while(!q.empty()){
int dist=q.front().first;
int x=q.front().second.first, y=q.front().second.second;
q.pop();
if(dist<mij)
for(int i=0;i<4;i++){
int ni=x+dx[i], nj=y+dy[i];
if(!viz[ni][nj]&&m[ni][nj]==0){
viz[ni][nj]=1;
q.push({dist+1,{ni,nj}});
}
}
}
if(!viz[is][js]&&!viz[ir][jr]){
viz[is][js]=1;
queue <pair <int,int>> q1;
q1.push({is,js});
while(!q1.empty()){
int x=q1.front().first, y=q1.front().second;
q1.pop();
if(x==ir&&y==jr)
break;
for(int k=0;k<4;k++){
int ni=x+dx[k], nj=y+dy[k];
if(!viz[ni][nj]&&m[ni][nj]==0){
viz[ni][nj]=1;
q1.push({ni,nj});
}
}
}
if(viz[ir][jr]) s=mij;
else d=mij-1;
}
else d=mij-1;
}
if(s==d) fout<<s;
else fout<<-1;
return 0;
}