Pagini recente » Cod sursa (job #578659) | Cod sursa (job #150778) | Cod sursa (job #1332182) | Cod sursa (job #572897) | Cod sursa (job #3122159)
#include <iostream>
#include <fstream>
#include <queue>
using namespace std;
ifstream fin("barbar.in");
ofstream fout("barbar.out");
struct cel {
int x, y;
};
const short NMAX = 1000;
const short dx[] = {-1, 0, 1, 0};
const short dy[] = {0, 1, 0, -1};
char a[NMAX+5][NMAX+5];
int d[NMAX+5][NMAX+5];
short n, m;
cel in, out;
queue<cel> q;
void clear()
{
while (!q.empty()) q.pop();
}
bool valid(cel z)
{
return z.x >= 1 && z.x <= n && z.y >= 1 && z.y <= n;
}
bool ok(short val)
{
if (d[in.x][in.y] < val) return false;
q.push({in.x, in.y});
while (!q.empty()) {
cel z = q.front();
q.pop();
if (z.x == out.x && z.y == out.y) {
clear();
return true;
}
for (short dir = 0; dir < 4; dir++) {
cel t = {z.x+dx[dir], z.y+dy[dir]};
if (valid(t) && d[t.x][t.y] >= val && d[t.x][t.y] != -1) q.push({t.x, t.y});
}
}
return false;
}
int main()
{
fin>>n>>m;
for (short i = 1; i <= n; i++)
for (short j = 1; j <= m; j++) {
fin>>a[i][j], d[i][j] = -2;
if (a[i][j] == 'D') d[i][j] = 0, q.push({i, j});
if (a[i][j] == '*') d[i][j] = -1;
if (a[i][j] == 'I') in = {i, j};
if (a[i][j] == 'O') out = {i, j};
}
while (!q.empty()) {
cel z = q.front();
q.pop();
for (short dir = 0; dir < 4; dir++) {
cel t = {z.x+dx[dir], z.y+dy[dir]};
if (valid(t) && d[t.x][t.y] == -2) q.push({t.x, t.y}), d[t.x][t.y] = d[z.x][z.y]+1;
}
}
short l = 0, r = n+m, sol = -1;
while (l <= r) {
short mid = (l+r)/2;
if (ok(mid)) sol = mid, l = mid+1;
else r = mid-1;
}
fout<<sol;
return 0;
}