Pagini recente » Cod sursa (job #375348) | Cod sursa (job #388288) | Cod sursa (job #157596) | Cod sursa (job #879472) | Cod sursa (job #2332827)
#include <iostream>
#include <fstream>
#include <queue>
#define fi first
#define se second
using namespace std;
const int Maxx=1e3+1;
const int dx[]={-1,0,1,0};
const int dy[]={0,1,0,-1};
struct POINT{
int x,y;
}nw,ac,str,stp;
queue <POINT> Q;
queue < pair<int,int> > q;
ifstream fin("barbar.in");
ofstream fout("barbar.out");
int n,m,i,j,val=-1,ans=0;
int dist[Maxx][Maxx];
bool A[Maxx][Maxx];
char a;
bool test1(pair <int,int> f);
bool test(POINT a);
bool lee(int val),ok=false;
int main() {
fin>>n>>m;
for (i=1;i<=n;++i){
for (j=1;j<=m;++j){
fin>>a;
if (a=='I'){
str.x=i;
str.y=j;
}
if (a=='O'){
stp.x=i;
stp.y=j;
}
if (a=='*'){
dist[i][j]=-1;
}
if (a=='D'){
A[i][j]=-1;
q.push({i,j});
dist[i][j]=1;
}
}
}
pair <int,int> f,g;
int d;
while (!q.empty()){
f=q.front();
q.pop();
for (d=0;d<4;++d){
g.fi=f.fi+dx[d];
g.se=f.se+dy[d];
if (test1(g) && dist[g.fi][g.se]==0){
dist[g.fi][g.se]=dist[f.fi][f.se]+1;
val=max(val,dist[g.fi][g.se]);
q.push(g);
}
}
}
for (i=1;i<=n;++i) for (j=1;j<=m;++j) --dist[i][j];
for (i=19;i>=0;--i){
if (ans+(1<<i)<=10000 && lee(ans+(1<<i))){
ans+=(1<<i);
}
}
fout<<ans;
return 0;
}
bool test1(pair <int,int> f){
return f.fi>0 && f.fi<=n && f.se>0 && f.se<=m;
}
bool test(POINT a){
return a.x>0 && a.x<=n && a.y>0 && a.y<=m;
}
bool lee(int val){
if (dist[nw.x][nw.y]>val) return 0;
for (int i=1;i<=n;++i) for (int j=1;j<=m;++j) A[i][j]=0;
Q.push(str);
A[str.x][str.y]=1;
int d;
while (!Q.empty()){
ac=Q.front();
Q.pop();
//fout<<ac.x<<" "<<ac.y<<"\n";
for (d=0;d<4;++d){
nw.x=ac.x+dx[d];
nw.y=ac.y+dy[d];
if (test(nw) && dist[nw.x][nw.y]>=val && !A[nw.x][nw.y] && dist[nw.x][nw.y]!=-1){
if (nw.x==stp.x && nw.y==stp.y){
while (!Q.empty()) Q.pop();
return 1;
}
A[nw.x][nw.y]=1;
Q.push(nw);
}
}
}
return 0;
}