Pagini recente » Cod sursa (job #2731650) | Cod sursa (job #2168032) | Cod sursa (job #1019852) | Cod sursa (job #494512) | Cod sursa (job #1750695)
#include <cstdio>
#include <queue>
#define in "barbar.in"
#define out "barbar.out"
#define NMAX (1000 + 7)
using namespace std;
int R, C, sol, px, py, lim, dirX[5] = {0, 1, 0, -1, 0}, dirY[5] = {0, 0, 1, 0, -1};
char mat[NMAX][NMAX], aux[NMAX][NMAX];
bool smth;
struct stare
{
int x;
int y;
int p;
};
queue <stare> bfs;
void expand()
{
stare tmp, newbie;
while(!bfs.empty())
{
tmp = bfs.front();
bfs.pop();
if(tmp.p == lim) continue;
for(int i = 1; i<= 4; ++i)
{
int p1 = tmp.x + dirX[i], p2 = tmp.y + dirY[i];
if(aux[p1][p2] == 0 || aux[p1][p2] == 5)
{
aux[p1][p2] = -1;
newbie.x = p1;
newbie.y = p2;
newbie.p = tmp.p + 1;
bfs.push(newbie);
}
if(p1 == px && p2 == py)
{
smth = 1;
}
}
}
}
bool way(const int &X, const int &Y)
{
bool check = 0;
for(int i = 1; i<= 4; ++i)
{
int p1 = X + dirX[i], p2 = Y + dirY[i];
if(aux[p1][p2] == 0)
{
aux[p1][p2] = -1;
if(way(p1, p2)) check = 1;
}
if(aux[p1][p2] == 5) return 1;
}
return check;
}
bool vef(const int &dist) /// nu e optim
{
for(int i = 0; i<= R+1; ++i) aux[i][0] = aux[i][C+1] = -1;
for(int i = 0; i<= C+1; ++i) aux[0][i] = aux[R+1][i] = -1;
for(int i = 1; i<= R; ++i)
{
for(int j = 1; j<= C; ++j)
{
if(mat[i][j] == '.') aux[i][j] = 0; ///liber
if(mat[i][j] == '*') aux[i][j] = -1; ///ocupat
if(mat[i][j] == 'D') aux[i][j] = 1; ///dragon
if(mat[i][j] == 'I')
{
aux[i][j] = -1;
px = i;
py = j;
}
if(mat[i][j] == 'O') aux[i][j] = 5; ///iesire
}
}
smth = 0;
lim = dist;
stare tmp;
tmp.p = 1;
for(int i = 1; i<= R; ++i)
{
for(int j = 1; j<= C; ++j)
{
if(aux[i][j] == 1)
{
tmp.x = i;
tmp.y = j;
bfs.push(tmp);
}
}
}
expand();
if(smth) return 0;
/*for(int i = 1; i<= R; ++i)
{
for(int j = 1; j<= C; ++j)
{
if(i == px && j == py) {printf("P");continue;}
if(aux[i][j] == -1) printf("X");
else printf("%d", aux[i][j]);
}
printf("\n");
}*/
if(way(px, py)) return 1;
return 0;
}
inline void citire()
{
scanf("%d %d", &R, &C);
for(int i = 1; i<= R; ++i)
{
scanf("%s", mat[i]+1);
}
}
int cautbin()
{
//printf("check enter\n");
int start = 0, finish = R*C, step = 1;
for( ; step <= finish; step<<=1);
step >>= 1;
for( ; step; step>>=1)
{
int index = start + step;
//printf("check start = %d step = %d\n", start, step);
if(index > finish) continue;
if(vef(index)) start = index;
}
return start;
}
int main()
{
freopen(in, "r", stdin);
freopen(out, "w", stdout);
citire();
sol = cautbin();
printf("%d\n", sol);
return 0;
}