Pagini recente » Cod sursa (job #91834) | Cod sursa (job #2317595) | Cod sursa (job #1849824) | Cod sursa (job #704421) | Cod sursa (job #1149429)
#include <fstream>
#include <queue>
#include <algorithm>
#include <vector>
#define NMAX 1005
#define oo (1<<30)
#define PII pair<int,int>
using namespace std;
ifstream in("barbar.in");
ofstream out("barbar.out");
int n, m, xi, yi, xf, yf;
int v[NMAX][NMAX], dragons[NMAX][NMAX];
int dx[] = {0, 1, 0, -1}, dy[] = {1, 0, -1, 0};
queue<short> L, C;
bool use[NMAX][NMAX], inqueue[NMAX][NMAX];
const int SZ = 1005;
char x[SZ];
struct coord_cmp {
bool operator()(PII &a, PII &b) {
return dragons[a.first][a.second] < dragons[b.first][b.second];
}
};
priority_queue<PII, vector<PII>, coord_cmp> heap;
void lee();
void borders();
void path();
int main(int argc, char *argv[])
{
in >> n >> m;
in.get();
for (int i = 1; i <= n; ++i) {
in.getline(x + 1, SZ);
for (int j = 1; j <= m; ++j) {
switch (x[j]) {
case '*':
v[i][j] = -1;
dragons[i][j] = -1;
break;
case 'D':
L.push(i);
C.push(j);
dragons[i][j] = 1;
break;
case 'I':
xi = i;
yi = i;
break;
case 'O':
xf = i;
yf = j;
break;
default:
break;
}
}
}
borders();
lee();
path();
if (!v[xf][yf])
out << "-1\n";
else
out << v[xf][yf] - 1 << "\n";
in.close();
out.close();
return 0;
}
void lee()
{
for (int r, c; L.size(); L.pop(), C.pop()) {
r = L.front();
c = C.front();
for (int i = 0; i < 4; ++i) {
int ii = r + dx[i];
int jj = c + dy[i];
if (dragons[ii][jj])
continue;
dragons[ii][jj] = dragons[r][c] + 1;
L.push(ii);
C.push(jj);
}
}
}
void borders()
{
for (int i = 0; i <= n + 1; ++i)
v[i][0] = v[i][m + 1] = dragons[i][0] = dragons[i][m + 1] = -1;
for (int i = 0; i <= m + 1; ++i)
v[0][i] = v[n + 1][i] = dragons[0][i] = dragons[n + 1][i] = -1;
}
void path()
{
v[xi][yi] = dragons[xi][yi];
heap.push(make_pair(xi, yi));
for (int r, c; heap.size();) {
r = heap.top().first;
c = heap.top().second;
heap.pop();
if (use[r][c])
continue;
use[r][c] = 1;
if (r == xf && c == yf)
return;
for (int i = 0; i < 4; ++i) {
int ii = r + dx[i];
int jj = c + dy[i];
if (use[ii][jj] || v[ii][jj] == -1)
continue;
v[ii][jj] = max(v[ii][jj], min(v[r][c], dragons[ii][jj]));
if (!heap.size() || !inqueue[ii][jj]) {
heap.push(make_pair(ii, jj));
inqueue[ii][jj] = 1;
}
else {
pair<short, short> x = heap.top();
heap.pop();
heap.push(x);
}
}
}
}