Pagini recente » Cod sursa (job #508475) | Cod sursa (job #42608) | Cod sursa (job #1721559) | Cod sursa (job #2525081) | Cod sursa (job #2665125)
#include <bits/stdc++.h>
#define N 1000
#define M 1000
using namespace std;
int a[N + 1][M + 1];
const int di[] = {-1, 0, 1, 0}, dj[] = {0, 1, 0, -1}; // NESV
void BFS (queue <pair <int, int>> &Q) {
while (!Q.empty()) {
auto save = Q.front();
Q.pop();
pair <int, int> nou;
int k;
for (k = 0; k < 4; k++) {
nou = {save.first + di[k], save.second + dj[k]};
if (!a[nou.first][nou.second]) {
a[nou.first][nou.second] = a[save.first][save.second] + 1; // a[i][j] = distanta minima de la camera {i, j} la un dragon
Q.push(nou);
}
}
}
}
int dist[N + 1][M + 1];
class heap {
public:
int lin, col, cost;
heap (const int &_lin, const int &_col, const int &_cost) : lin(_lin), col(_col), cost(_cost) {}
bool operator < (const heap &x) const {
return cost < x.cost;
}
};
int main () {
freopen("barbar.in", "r", stdin);
freopen("barbar.out", "w", stdout);
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
int n, m;
cin >> n >> m;
memset(a, 0xFF, sizeof a); // a[][] = -1
char c;
pair <int, int> start, finish;
queue <pair <int, int>> Q;
int i, j;
for (i = 1; i <= n; i++)
for (j = 1; j <= m; j++) {
cin >> c;
switch (c) {
case '.':
a[i][j] = 0;
break;
case 'I':
a[i][j] = 0;
start = make_pair(i, j);
break;
case 'D':
a[i][j] = 0;
Q.emplace(i, j);
break;
case 'O':
a[i][j] = 0;
finish = make_pair(i, j);
break;
}
}
BFS(Q);
priority_queue <heap> PQ; // max heap
PQ.emplace(start.first, start.second, a[start.first][start.second]);
dist[start.first][start.second] = a[start.first][start.second];
int ans = -1;
while (!PQ.empty() && ans == -1) {
auto save = PQ.top();
PQ.pop();
if (save.lin == finish.first && save.col == finish.second)
ans = save.cost;
else
if (dist[save.lin][save.col] == save.cost) {
pair <int, int> nou;
int k;
for (k = 0; k < 4; k++) {
nou = {save.lin + di[k], save.col + dj[k]};
if (a[nou.first][nou.second] != -1)
if (dist[nou.first][nou.second] < min(save.cost, a[nou.first][nou.second])) {
dist[nou.first][nou.second] = min(save.cost, a[nou.first][nou.second]);
PQ.emplace(nou.first, nou.second, min(save.cost, a[nou.first][nou.second]));
}
}
}
}
cout << ans;
return 0;
}