Pagini recente » Cod sursa (job #78581) | Cod sursa (job #2988165)
#include <bits/stdc++.h>
#define oo 2e9
using namespace std;
ifstream fin("barbar.in");
ofstream fout("barbar.out");
char a[1005][1005];
int d[1005][1005];
bool b[1005][1005];
int n, m;
int xs, ys, xf, yf;
int dx[] = {-1, 0, 0, 1};
int dy[] = {0, -1, 1, 0};
queue<pair<int, int>> q;
void Lee()
{
int i, j, x, y;
while (!q.empty())
{
i = q.front().first;
j = q.front().second;
q.pop();
for (int k = 0; k < 4; k++)
{
x = i + dx[k];
y = j + dy[k];
if (a[x][y] != '*' && d[x][y] > d[i][j] + 1)
{
d[x][y] = d[i][j] + 1;
q.push({x, y});
}
}
}
}
void Fill(int DisMin)
{
int i, j, x, y;
for (i = 1; i <= n; i++)
for (j = 1; j <= m; j++)
b[i][j] = 0;
b[xs][ys] = 1;
q.push({xs, ys});
while (!q.empty())
{
i = q.front().first;
j = q.front().second;
q.pop();
for (int k = 0; k < 4; k++)
{
x = i + dx[k];
y = j + dy[k];
if (a[x][y] != '*' && d[x][y] >= DisMin && b[x][y] == 0)
{
b[x][y] = 1;
q.push({x, y});
}
}
}
}
void Rezolvare()
{
int st, dr, mij, DisMax;
st = 0; dr = 2e5;
DisMax = 0;
while (st <= dr)
{
mij = (st + dr) / 2;
Fill(mij);
if (b[xf][yf] == 1)
{
DisMax = mij;
st = mij + 1;
}
else dr = mij - 1;
}
if (DisMax == 0)fout << "-1\n";
else fout << DisMax << "\n";
}
int main()
{
int i, j;
fin >> n >> m;
for (i = 1; i <= n; i++)
fin >> (a[i] + 1);
for (i = 0; i <= n + 1; i++)
a[i][0] = a[i][m + 1] = '*';
for (j = 0; j <= m + 1; j++)
a[0][j] = a[n + 1][j] = '*';
for (i = 1; i <= n; i++)
for (j = 1; j <= m; j++)
d[i][j] = oo;
for (i = 1; i <= n; i++)
for (j = 1; j <= m; j++)
if (a[i][j] == 'D')
{
q.push({i, j});
d[i][j] = 0;
}
else if (a[i][j] == 'I')
{
xs = i; ys = j;
}
else if (a[i][j] == 'O')
{
xf = i; yf = j;
}
Lee();
for (i = 0; i <= n + 1; i++)
b[i][0] = b[i][m + 1] = 1;
for (j = 0; j <= m + 1; j++)
b[0][j] = b[n + 1][j] = 1;
Rezolvare();
return 0;
}