Pagini recente » Cod sursa (job #2973186) | Cod sursa (job #3199875) | Cod sursa (job #408510) | Cod sursa (job #158807) | Cod sursa (job #1140404)
#include <fstream>
#include <queue>
using namespace std;
ifstream in("barbar.in");
ofstream out("barbar.out");
int m, n, i1, j1, i2, j2;
struct pozitie
{
int lin,col;
};
char v[1001][1001];
int d[1001][1001];
int c[1001][1001];
queue <pozitie> q;
const int dlin[] = {-1,0,1,0};
const int dcol[] = {0,1,0,-1};
bool drum(int dist)
{
int i, j;
pozitie x, y;
for(i = 1; i <= m; i++)
for(j = 1; j <= n; j++)
if(d[i][j] < dist)
c[i][j] = -1;
else
c[i][j] = 0;
if(c[i1][j1] == -1)
return 0;
c[i1][j1] = 1;
c[i2][j2] = 0;
q.push((pozitie){i1, j1});
while(!q.empty())
{
x = q.front();
q.pop();
for(i = 0; i < 4; i++)
{
y.lin = x.lin + dlin[i];
y.col = x.col + dcol[i];
if(v[y.lin][y.col] != NULL && c[y.lin][y.col] == 0)
{
c[y.lin][y.col] = 1;
q.push(y);
}
}
}
if(c[i2][j2] == 1)
return 1;
return 0;
}
int main()
{
int i, j, pas;
pozitie x, y;
in>>m>>n;
for(i = 1; i <= m; i++)
in>>(1 + v[i]);
for(i = 1; i <= m; i++)
for(j = 1; j <= n; j++)
if(v[i][j] == 'D')
{
d[i][j] = 1;
q.push((pozitie){i,j});
}
else if(v[i][j] == 'I')
{
i1 = i;
j1 = j;
}
else if(v[i][j] == 'O')
{
i2 = i;
j2 = j;
}
while(!q.empty())
{
x = q.front();
q.pop();
for(i = 0; i < 4; i++)
{
y.lin = x.lin + dlin[i];
y.col = x.col + dcol[i];
if(v[y.lin][y.col] != NULL && d[y.lin][y.col] == 0)
{
d[y.lin][y.col] = 1 + d[x.lin][x.col];
q.push(y);
}
}
}
for(i = 1; i <= m; i++)
for(j = 1; j <= n; j++)
if(v[i][j] == '*' || v[i][j] == 'D')
d[i][j] = -1;
else
d[i][j]--;
i = 0;
pas = 1 << 19;
while(pas)
{
if(drum(i + pas))
i += pas;
pas /= 2;
}
if(drum(i))
out<<i<<'\n';
else
out<<-1<<'\n';
return 0;
}