Pagini recente » Cod sursa (job #1208) | Cod sursa (job #1238401) | Cod sursa (job #208788) | Cod sursa (job #657960) | Cod sursa (job #3201567)
#include <bits/stdc++.h>
using namespace std;
ifstream fin("barbar.in");
ofstream fout("barbar.out");
const int nmax=1e3,INF=79797979;
char ch[nmax+1][nmax+1];
int dst[nmax+1][nmax+1];
bool a[nmax+1][nmax+1];
int dx[]= {-1,0,1,0};
int dy[]= {0,-1,0,1};
queue<pair<int,int>> q;
int n,m,xi,yi,xf,yf,maxd=0;
void read() {
fin>>n>>m;
for(int i=1; i<=n; i++) {
for(int j=1; j<=m; j++) {
dst[i][j]=INF;
fin>>ch[i][j];
if(ch[i][j]=='I') {
xi=i;
yi=j;
} else if(ch[i][j]=='O') {
xf=i;
yf=j;
dst[i][j]=INF;
} else if(ch[i][j]=='D') {
q.push({i,j});
dst[i][j]=0;
}
}
}
}
bool in(int x,int y) {
return (x>=1&&x<=n&&y>=1&&y<=m);
}
void clean() {
for(int i=1; i<=n; i++) {
for(int j=1; j<=m; j++)
a[i][j]=0;
}
}
void bfs() {
while(!q.empty()) {
auto cur=q.front();
int cx=cur.first,cy=cur.second;
q.pop();
for(int i=0; i<4; i++) {
int nx=cx+dx[i],ny=cy+dy[i];
if(in(nx,ny)&&ch[nx][ny]=='.'&&dst[nx][ny]>dst[cx][cy]) {
dst[nx][ny]=dst[cx][cy]+1;
q.push({nx,ny});
}
}
maxd=max(maxd,dst[cx][cy]);
}
}
bool works(int x){
clean();
while(!q.empty())
q.pop();
q.push({xi,yi});
a[xi][yi]=1;
while(!q.empty()){
auto cur=q.front();
int cx=cur.first,cy=cur.second;
//fout<<cx<<" "<<cy<<", ";
if(cx==xf&&cy==yf){
return 1;
}
q.pop();
for(int i=0; i<4; i++) {
int nx=cx+dx[i],ny=cy+dy[i];
if(in(nx,ny)&&(ch[nx][ny]=='.'||ch[nx][ny]=='O')&&dst[nx][ny]>=x&&a[nx][ny]==0) {
a[nx][ny]=1;
q.push({nx,ny});
}
}
}
return 0;
}
int cautbin() {
int st=1,dr=maxd,last=1,mid;
while(st<=dr) {
mid=(st+dr)/2;
//fout<<"\n"<<mid<<": ";
if(works(mid)) {
last=mid;
st=mid+1;
} else
dr=mid-1;
}
return last;
}
int main() {
read();
bfs();
fout<<cautbin();
return 0;
}