Pagini recente » Cod sursa (job #3208006) | Cod sursa (job #854718) | Cod sursa (job #307538) | Cod sursa (job #2297673) | Cod sursa (job #1729564)
#include <fstream>
#include <queue>
#include <iostream> // sterge
using namespace std;
ifstream fin("barbar.in");
ofstream fout("barbar.out");
int n, m, stx, sty, sfx, sfy;
int dx[4] = {-1, 0, 1, 0};
int dy[4] = {0, 1, 0, -1};
int a[1002][1002], b[1002][1002];
const int inf = 1<<30;
struct Element {
int ab, ord;
}aux, work;
queue <Element> q;
void read() {
char c;
fin >> n >> m;
for (int i=1; i<=n; i++) {
for (int j=1; j<=m; j++) {
fin >> c;
if (c == 'I') {
a[i][j] = inf;
stx = i;
sty = j;
}
else if (c == 'O') {
a[i][j] = inf;
sfx = i;
sfy = j;
}
else if (c == 'D') {
a[i][j] = 0;
Element x;
x.ab = i;
x.ord = j;
q.push(x);
}
else if (c == '*') {
a[i][j] = -1;
}
else
a[i][j] = inf;
}
}
for (int i=0; i<=n+1; i++)
a[i][0] = a[i][m+1] = -1;
for (int j=0; j<=m+1; j++)
a[0][j] = a[n+1][j] = -1;
}
void dragons() {
Element x, t;
while (!q.empty()){
x = q.front();
q.pop();
for (int i = 0; i < 4; ++i) {
int newx = x.ab + dx[i];
int newy = x.ord + dy[i];
if (a[newx][newy] > a[x.ab][x.ord] + 1) {
a[newx][newy] = a[x.ab][x.ord] + 1;
t.ab = newx;
t.ord = newy;
q.push(t);
}
}
}
}
void clean() {
for (int i=0; i<=n+1; i++)
for (int j=0; j<=m+1; j++)
if (a[i][j] >= 0)
b[i][j] = inf;
else
b[i][j] = -1;
}
int drum(int k) {
clean();
aux.ab = stx;
aux.ord = sty;
b[stx][sty] = 0;
if (a[stx][sty] < k)
return 0;
q.push(aux);
while (!q.empty()) {
aux = q.front();
q.pop();
if (sfx == aux.ab && sfy == aux.ord) {
return 1;
}
for (int i=0; i<4; i++) {
work.ab = aux.ab + dx[i];
work.ord = aux.ord + dy[i];
if (a[work.ab][work.ord] >= k && b[aux.ab][aux.ord] + 1 < b[work.ab][work.ord]) {
q.push(work);
b[work.ab][work.ord] = b[aux.ab][aux.ord] + 1;
}
}
}
return 0;
}
int caut (int st, int dr) {
int mij, ras=-1;
while (st < dr) {
mij = (st + dr) / 2;
if (drum(mij) == 1) {
st = mij + 1;
ras = mij;
}
else
dr = mij;
}
return ras;
}
int main() {
int big;
read();
dragons();
big = 2 * max(n, m) - 2;
fout << caut(0, big);
return 0;
}