Pagini recente » Cod sursa (job #1559262) | arena | Istoria paginii runda/oji.2k162 | Istoria paginii runda/fanninfo/clasament | Cod sursa (job #1081462)
//
// main.cpp
// barbar
//
// Created by Catalina Brinza on 1/10/14.
// Copyright (c) 2014 Catalina Brinza. All rights reserved.
//
#include <fstream>
#include <queue>
#define nru 1001
using namespace std;
ifstream in("barbar.in");
ofstream out("barbar.out");
struct ind
{
int d,c;
};
int a[nru][nru],C,r,z,t;
bool viz[nru][nru];
queue<ind> q;
ind kn;
void initializare()
{int i,j;
for (i=1;i<=r;++i) for (j=1;j<=C;++j) a[i][j]=false;
}
void perfeeect(int i,int j,int m)
{ind w;
if (i!=1 && a[i-1][j]>=m && !viz[i-1][j])
{
viz[i-1][j]=true;
w.c=i-1;
w.d=j;
q.push(w);
}
if (i!=r && a[i+1][j]>=m && !viz[i+1][j])
{
viz[i+1][j]=true;
w.c=i+1;
w.d=j;
q.push(w);
}
if (j!=1 && a[i][j-1]>=m && !viz[i][j-1])
{
viz[i][j-1]=true;
w.c=i;
w.d=j-1;
q.push(w);
}
if (j!=C && a[i][j+1]>=m && !viz[i][j+1])
{
q.push(w);
viz[i][j+1]=true;
w.c=i;
w.d=j+1;
}
return;
}
int main(int argc, const char * argv[])
{int i,j,x,y,z,t,k,l;
char car;
ind w;
in>>r>>C;
initializare();
for (i=1;i<=r;++i)
for (j=1;j<=C;++j)
{
in>>car;
if (car=='I')
{
x=i; y=j;a[i][j]=-1;
}
else if (car=='O')
{
z=i;
t=j;
a[i][j]=-1;
}
else if (car=='D') {
a[i][j]=0;
w.c=i;
w.d=j;
viz[i][j]=true;
q.push(w);
}
else if (car=='*') a[i][j]=-2;
else
a[i][j]=-1;
}
while (!q.empty())
{
i=q.front().c;
j=q.front().d;
if (i!=1 && a[i-1][j]==-1 && !viz[i][j-1])
{
a[i-1][j]=a[i][j]+1;
viz[i-1][j]=true;
w.c=i-1;
w.d=j;
q.push(w);
}
if (i!=r && a[i+1][j]==-1 && !viz[i+1][j])
{viz[i+1][j]=true;
a[i+1][j]=a[i][j]+1;
w.c=i+1;
w.d=j;
q.push(w);
}
if (j!=1 && a[i][j-1]==-1 && !viz[i][j-1])
{
viz[i][j-1]=true;
a[i][j-1]=a[i][j]+1;
w.c=i;
w.d=j-1;
q.push(w);
}
if (j!=C && a[i][j+1]==-1 && !viz[i][j+1])
{viz[i][j+1]=true;
a[i][j+1]=a[i][j]+1;
w.c=i;
w.d=j+1;
q.push(w);
}
q.pop();
}
// for (i=1;i<=r;++i) {for (j=1;j<=C;++j) out<<a[i][j]<<' ';out<<"\n";}
i=x;j=y;
// out<<x<<' '<<y<<' '<<z<<' '<<t<<"\n";
int min=-1,max=a[x][y],mij; bool ok2=false;
if (a[i][j]>a[z][t]) max=a[z][t];
while (max>min+1)
{
initializare();
mij=min+(max-min)/2;
// out<<min<<' '<<mij<<' '<<max<<"\n";
w.c=x;
w.d=y;
q.push(w);
while (!q.empty())
{
perfeeect(q.front().c,q.front().d,mij);
if (viz[z][t])
{
while(!q.empty()) q.pop();
break;
}
q.pop();
}
if (viz[z][t]) min=mij;
else max=mij-1;
}
if (max==min+1)
{
initializare();
mij=min;
// out<<min<<' '<<mij<<' '<<max<<"\n";
w.c=x;
w.d=y;
q.push(w);
while (!q.empty())
{
perfeeect(q.front().c,q.front().d,mij);
if (viz[z][t])
{
while(!q.empty()) q.pop();
break;
}
q.pop();
}
if (viz[z][t]) ok2=true;
initializare();
mij=min+1;
// out<<min<<' '<<mij<<' '<<max<<"\n";
w.c=x;
w.d=y;
q.push(w);
while (!q.empty())
{
perfeeect(q.front().c,q.front().d,mij);
if (viz[z][t])
{
while(!q.empty()) q.pop();
break;
}
q.pop();
}
if (viz[z][t] && ok2) out<<min+1;
else out<<min;
}
else out<<min;
return 0;
}