Pagini recente » Cod sursa (job #115058) | Cod sursa (job #1717823) | Cod sursa (job #1786036) | Cod sursa (job #1676229) | Cod sursa (job #3273306)
#include <bits/stdc++.h>
#define NMAX 1000
using namespace std;
ifstream fin("barbar.in");
ofstream fout("barbar.out");
int n, m, xi, yi, xo, yo, dist[NMAX + 2][NMAX + 2], tr[NMAX + 2][NMAX + 2], cnt;
int st, dr, mij, ans = INT_MAX;
char mat[NMAX + 2][NMAX + 2];
int dx[4] = {-1, 1, 0, 0};
int dy[4] = {0, 0, -1, 1};
queue<pair<int, int>> qd;
bool inmat(int l, int c) {
return l >= 1 && l <= n && c >= 1 && c <= m;
}
int main()
{
fin >> n >> m;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
fin >> mat[i][j];
dist[i][j] = INT_MAX;
if (mat[i][j] == 'I') {
xi = i;
yi = j;
}
if (mat[i][j] == 'O') {
xo = i;
yo = j;
}
if (mat[i][j] == 'D') {
qd.push({i, j});
dist[i][j] = 0;
}
}
}
while (!qd.empty()) {
int lin = qd.front().first;
int col = qd.front().second;
qd.pop();
for (int dir = 0; dir < 4; dir++) {
int newlin = lin + dx[dir];
int newcol = col + dy[dir];
if (inmat(newlin, newcol) && mat[newlin][newcol] != '*' && dist[lin][col] + 1 < dist[newlin][newcol]) {
dist[newlin][newcol] = dist[lin][col] + 1;
qd.push({newlin, newcol});
}
}
}
st = 1, dr = (NMAX + 2) * (NMAX + 2);
while (st <= dr) {
mij = (st + dr) >> 1;
cnt++;
if (mij <= dist[xi][yi]) {
queue<pair<int, int>> q;
q.push({xi, yi});
tr[xi][yi] = cnt;
while (!q.empty()) {
int lin = q.front().first;
int col = q.front().second;
q.pop();
for (int dir = 0; dir < 4; dir++) {
int newlin = lin + dx[dir];
int newcol = col + dy[dir];
if (inmat(newlin, newcol) && mat[newlin][newcol] != '*' && mat[newlin][newcol] != 'D' && mij <= dist[newlin][newcol] && tr[newlin][newcol] != cnt) {
tr[newlin][newcol] = cnt;
q.push({newlin, newcol});
}
}
}
}
if (tr[xo][yo] == cnt) {
ans = mij;
st = mij + 1;
}
else {
dr = mij - 1;
}
}
if (ans != INT_MAX) {
fout << ans;
}
else {
fout << -1;
}
return 0;
}