Pagini recente » Cod sursa (job #1443946) | Cod sursa (job #333890) | Cod sursa (job #1245964) | Cod sursa (job #1640265) | Cod sursa (job #2017593)
#include <iostream>
#include <fstream>
#include <queue>
#include <vector>
#include <assert.h>
using namespace std;
ifstream in("barbar.in");
ofstream out("barbar.out");
struct Waypoint {
int x, y, d;
};
struct Cell {
int x, y;
};
int dx[4] = {-1, 0, 1, 0};
int dy[4] = {0, 1, 0, -1};
int r, c;
Cell start, ex;
int dist[1001][1001], best[1001][1001];
bool pushed[1001][1001];
char a[1001][1001];
queue<Cell> q;
void calculate_distances() {
while (!q.empty()) {
Cell w = q.front(); q.pop();
int x = w.x, y = w.y;
for (int k = 0; k < 4; ++k) {
int i = x + dx[k];
int j = y + dy[k];
if (i >= 1 && i <= r && j >= 1 && j <= c) {
if ((a[i][j] == '.' || a[i][j] == 'I' || a[i][j] == 'O') && dist[i][j] == 0) {
dist[i][j] = dist[x][y] + 1;
q.push({i, j});
}
}
}
}
}
bool solve(int min_dist) {
bool reached = false;
if (dist[start.x][start.y] < min_dist) return false;
for (int i = 1; i <= r; ++i) {
for (int j = 1; j <= r; ++j) {
pushed[i][j] = false;
}
}
while (!q.empty()) q.pop();
q.push({start.x, start.y});
pushed[start.x][start.y] = true;
while (!q.empty()) {
Cell w = q.front(); q.pop();
int x = w.x, y = w.y;
if (x == ex.x && y == ex.y) {
reached = true;
break;
}
for (int k = 0; k < 4; ++k) {
int i = x + dx[k];
int j = y + dy[k];
if (i >= 1 && i <= r && j >= 1 && j <= c) {
if (!pushed[i][j] && dist[i][j] >= min_dist && a[i][j] != '*' && a[i][j] != 'D') {
pushed[i][j] = true;
q.push({i, j});
}
}
}
}
return reached;
}
int main()
{
in >> r >> c;
for (int i = 1; i <= r; ++i) {
for (int j = 1; j <= c; ++j) {
in >> a[i][j];
if (a[i][j] == 'I') {
start = {i, j};
} else if (a[i][j] == 'O') {
ex = {i, j};
} else if (a[i][j] == 'D') {
q.push({i, j});
}
}
}
calculate_distances();
int sol = 0;
int left = 0, right = r * c, mid;
while (left != right) {
mid = (left + right) / 2;
if (solve(mid)) {
left = mid + 1;
sol = mid;
} else {
right = mid;
}
}
if (sol == 0) out << -1; else
out << sol;
return 0;
}