Pagini recente » Cod sursa (job #2295990) | Cod sursa (job #394027) | Cod sursa (job #381912) | Cod sursa (job #2227639) | Cod sursa (job #1234153)
#include<fstream>
#include<cstring>
#include<queue>
using namespace std;
ifstream in("barbar.in");
ofstream out("barbar.out");
const int DMAX = 1005;
int d1[] = {0,1,-1,0};
int d2[] = {1,0,0,-1};
int v[DMAX][DMAX],sol[DMAX][DMAX],n,m;
bool viz[DMAX][DMAX];
struct punct{
int x,y;
};
struct punct start,finish;
queue<struct punct> coada;
inline void citire()
{
struct punct now;
char c;
in>>n>>m;
for(int i = 1 ; i <= n ; i++)
for(int j = 1 ; j <= m ; j++)
{
in>>c;
switch(c){
case '.':v[i][j] = 0;
break;
case '*':v[i][j] = 1;
break;
case 'D':{
v[i][j] = 1;
now.x = i;
now.y = j;
coada.push(now);
}
break;
case 'I':{
v[i][j] = 0;
start.x = i;
start.y = j;
}
break;
case 'O':{
v[i][j] = 0;
finish.x = i;
finish.y = j;
}
break;
}
}
for(int i = 0 ; i <= n+1 ; i++)
v[i][0] = v[i][m+1] = 1;
for(int j = 0 ; j <= m+1 ; j++)
v[0][j] = v[n+1][j] = 1;
in.close();
}
inline void parcurge()
{
struct punct now,k;
int i;
while(!coada.empty()){
k = coada.front();
viz[k.x][k.y] = true;
for(i = 0 ; i < 4 ; i++){
now.x = k.x+d1[i];
now.y = k.y+d2[i];
if(!viz[now.x][now.y] && v[now.x][now.y] == 0){
sol[now.x][now.y] = sol[k.x][k.y] + 1;
coada.push(now);
}
}
coada.pop();
}
}
inline bool ok(int val)
{
memset(viz,0,sizeof(viz));
struct punct now,k;
coada.push(start);
if(sol[start.x][start.y] < val)
return false;
int i;
while(!coada.empty())
{
k = coada.front();
viz[k.x][k.y] = 1;
for(i = 0 ; i < 4 ; i++)
{
now.x = k.x+d1[i];
now.y = k.y+d2[i];
if(!viz[now.x][now.y] && sol[now.x][now.y] >= val && v[now.x][now.y] == 0){
if(finish.x == now.x && finish.y == now.y)
return true;
coada.push(now);
}
}
coada.pop();
}
return false;
}
inline void solve()
{
for(int i = sol[finish.x][finish.y] ; i >= 1 ; i --)
if(ok(i)){
out<<i;
return;
}
out<<-1;
}
int main()
{
citire();
parcurge();
solve();
return 0;
}