Pagini recente » Cod sursa (job #1272270) | Cod sursa (job #572883) | Cod sursa (job #1244224) | Cod sursa (job #1681521) | Cod sursa (job #2987600)
#include <bits/stdc++.h>
using namespace std;
ifstream fin ("barbar.in");
ofstream fout ("barbar.out");
char a[1004][1004];
int d[1004][1004], v[1004][1004], n, m;
int xs, ys, xf, yf;
queue <pair <int, int> > q;
int dx[] = {-1, 1, 0, 0};
int dy[] = {0, 0, -1, 1};
void Citire ()
{
int i, j;
fin >> n >> m;
for (i = 1; i <= n; i++)
for (j = 1; j <= m; j++)
{
fin >> a[i][j];
d[i][j] = 2e9;
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;
}
fin.close();
}
void Border ()
{
int i;
for (i = 0; i <= n + 1; i++)
a[i][0] = a[i][m+1] = '*';
for (i = 1; i <= m; i++)
a[0][i] = a[n+1][i] = '*';
}
void Lee ()
{
int i, j, x, y, k;
while (!q.empty())
{
x = q.front().first;
y = q.front().second;
q.pop();
for (k = 0; k < 4; k++)
{
i = x + dx[k];
j = y + dy[k];
if (a[i][j] != '*' && d[i][j] > d[x][y] + 1)
{
q.push({i, j});
d[i][j] = d[x][y] + 1;
}
}
}
}
void Filll (int D)
{
int i, j, x, y, k;
q.push({xf, yf});
v[xf][yf] = 1;
while (!q.empty())
{
x = q.front().first;
y = q.front().second;
q.pop();
for (k = 0; k < 4; k++)
{
i = x + dx[k];
j = y + dy[k];
if (a[i][j] != '*' && d[i][j] >= D && v[i][j] == 0)
{
v[i][j] = 1;
q.push({i, j});
}
}
}
}
void Rez()
{
int i, j, low, high, mid, D;
low = 1; high = 1e6;
D = -1;
while (low <= high)
{
mid = (low + high) / 2;
for (i = 1; i <= n; i++)
for (j = 1; j <= m; j++)
v[i][j] = 0;
Filll (mid);
if (!v[xs][ys])
high = mid - 1;
else
{
D = mid;
low = mid + 1;
}
}
fout << D << "\n";
}
int main()
{
Citire();
Lee();
Rez();
fout.close();
return 0;
}