Pagini recente » Cod sursa (job #312460) | Cod sursa (job #3247531) | Cod sursa (job #1971180) | Cod sursa (job #2155172) | Cod sursa (job #2003709)
#include <fstream>
#include <deque>
#define DIM 1002
using namespace std;
ifstream f("barbar.in");
ofstream g("barbar.out");
int i, j, n, m, st, dr, ok, a[DIM][DIM], b[DIM][DIM], xi, yi, xf, yf, xc, yc, xin, yin, mid, okk;
int dx[] = {0, 0, 1, -1};
int dy[] = {1, -1, 0, 0};
struct abc
{
int x, y;
}aux;
deque <abc> c;
char ch;
int check(int x, int y)
{
if(x > n || x < 1 || y > m || y < 1)
return 0;
return 1;
}
int main()
{
f>>n>>m;
for(i = 1; i <= n; ++ i)
for(j = 1; j <= m; ++ j)
{
f>>ch;
if(ch == '*')
a[i][j] = -1;
if(ch == 'D')
{
aux.x = i;
aux.y = j;
c.push_back(aux);
a[i][j] = 1;
}
if(ch == 'I')
{
xin = i;
yin = j;
}
if(ch == 'O')
{
xf = i;
yf = j;
}
}
while(!c.empty())
{
aux = c.front();
xi = aux.x;
yi = aux.y;
for(i = 0;i <= 3; ++ i)
{
xc = xi + dx[i];
yc = yi + dy[i];
if(a[xc][yc] == 0 && check(xc, yc))
{
a[xc][yc] = a[xi][yi] + 1;
aux.x = xc;
aux.y = yc;
c.push_back(aux);
}
}
c.pop_front();
}
st = 1;
dr = max(n, m);
while(st <= dr)
{
mid = (st + dr) / 2;
c.clear();
aux.x = xin;
aux.y = yin;
c.push_back(aux);
ok = 0;
while(!c.empty() && ok == 0)
{
aux = c.front();
xi = aux.x;
yi = aux.y;
for(i = 0; i <= 3; ++ i)
{
xc = xi + dx[i];
yc = yi + dy[i];
if(a[xc][yc] >= mid && check(xc, yc) && b[xc][yc] != mid)
{
b[xc][yc] = mid;
aux.x = xc;
aux.y = yc;
c.push_back(aux);
if(xc == xf && yc == yf)
ok = 1;
}
}
c.pop_front();
}
if(ok == 1)
{
st = mid + 1;
okk = 1;
}
else
dr = mid - 1;
}
if(dr - 1 >= 0)
g<<dr-1;
else
g<<-1;
/*for(i = 1;i <= n; ++ i)
{
for(j = 1;j <= m; ++ j)
g<<a[i][j]<<" ";
g<<'\n';
}*/
return 0;
}