Pagini recente » Cod sursa (job #1055581) | Cod sursa (job #1590957) | Cod sursa (job #1230361) | Cod sursa (job #2432974) | Cod sursa (job #3251841)
#include <fstream>
#include <queue>
#include <climits>
using namespace std;
ifstream fin("barbar.in");
ofstream fout("barbar.out");
struct pos
{
int x, y;
int pas;
};
int n, m;
int maxx = INT_MIN;
int mat[1005][1005];
int d[4][2] = { {0, 1}, {1, 0}, {-1, 0}, {0, -1} };
int viz[1005][1005];
queue<pos> dragoni;
pos start, finish;
bool found = 0;
void leeDragoni()
{
while (!dragoni.empty())
{
for (int i = 0; i <= 3; i++)
{
int nx = dragoni.front().x + d[i][0], ny = dragoni.front().y + d[i][1];
if (nx < 1 || ny < 1 || nx > n || ny > m) continue;
if (mat[nx][ny] != 0) continue;
mat[nx][ny] = dragoni.front().pas - 1;
dragoni.push({nx, ny, dragoni.front().pas - 1});
}
dragoni.pop();
}
}
class Compare {
public:
bool operator()(pos a, pos b) {
if (a.pas > b.pas) {
return true;
}
return false;
}
};
priority_queue<pos, vector<pos>, Compare> q;
void priorityLee()
{
start.pas = mat[start.x][start.y];
q.push(start);
viz[start.x][start.y] = 1;
while (!q.empty())
{
int x = q.top().x;
int y = q.top().y;
int val = q.top().pas;
if (val > maxx)
{
maxx = val;
}
if (x == finish.x && y == finish.y)
{
found = 1;
break;
}
q.pop();
for (int i = 0; i <= 3; i++)
{
int nx = x + d[i][0], ny = y + d[i][1];
if (nx < 1 || ny < 1 || nx > n || ny > m) continue;
if (mat[nx][ny] >= 0 || viz[nx][ny] == 1) continue;
viz[nx][ny] = 1;
pos next;
next.x = nx;
next.y = ny;
next.pas = mat[nx][ny];
q.push(next);
}
}
}
int main()
{
fin >> n >> m;
char x;
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= m; j++)
{
fin >> x;
if (x == '.')
{
mat[i][j] = 0;
}
else if (x == 'I')
{
mat[i][j] = 0;
start.x = i;
start.y = j;
}
else if (x == 'O')
{
mat[i][j] = 0;
finish.x = i;
finish.y = j;
}
else if (x == 'D')
{
mat[i][j] = 4;
dragoni.push({ i, j, 0 });
}
else
{
mat[i][j] = 1;
}
}
}
leeDragoni();
priorityLee();
if (found)
{
fout << -maxx;
}
else
{
fout << -1;
}
}