Pagini recente » Cod sursa (job #2895304) | Cod sursa (job #311300) | Cod sursa (job #431015) | Cod sursa (job #412803) | Cod sursa (job #2871313)
#include <fstream>
#include <queue>
using namespace std;
const int N = 1000;
const int dl[] = {-1, 0, 1, 0};
const int dc[] = {0, -1, 0, 1};
int d[N+2][N+2], nl, nc;
pair <int, int> xi, xf;
bool accesibil[N+2][N+2];
bool ajung(int dist)
{
if (d[xi.first][xi.second] < dist)
{
return false;
}
queue < pair <int, int>> q;
for (int i = 1; i <= nl; i++)
{
for (int j = 1; j <= nc; j++)
{
accesibil[i][j] = true;
if (d[i][j] < dist)
{
accesibil[i][j] = false;
}
}
}
q.push(xi);
accesibil[xi.first][xi.second] = false;
while (!q.empty())
{
pair <int, int> x = q.front();
q.pop();
for (int i = 0; i < 4; i++)
{
pair <int, int> y = {x.first + dl[i], x.second + dc[i]};
if (accesibil[y.first][y.second])
{
if (y == xf)
{
return true;
}
accesibil[y.first][y.second] = false;
q.push(y);
}
}
}
return false;
}
int main()
{
ifstream in("barbar.in");
ofstream out("barbar.out");
queue < pair <int, int>> q;
in >> nl >> nc;
for (int i = 1; i <= nl; i++)
{
char lin[N+2];
in >> (1 + lin);
for (int j = 1; j <= nc; j++)
{
if (lin[j] == 'D')
{
q.push({i, j});
d[i][j] = 0;
}
else if (lin[j] == '*')
{
d[i][j] = -2;
}
else
{
if (lin[j] == 'I')
{
xi.first = i;
xi.second = j;
}
if (lin[j] == 'O')
{
xf.first = i;
xf.second = j;
}
d[i][j] = -1;
}
}
}
in.close();
while (!q.empty())
{
pair <int, int> x = q.front();
q.pop();
for (int i = 0; i < 4; i++)
{
pair <int, int> y = {x.first + dl[i], x.second + dc[i]};
if (d[y.first][y.second] == -1)
{
d[y.first][y.second] = 1 + d[x.first][x.second];
q.push(y);
}
}
}
int st = 0, dr = nl * nc, rez = -1;
while (st <= dr)
{
int m = (st + dr) / 2;
if (ajung(m))
{
rez = m;
st = m + 1;
}
else
{
dr = m - 1;
}
}
out << rez;
out.close();
return 0;
}