Pagini recente » Cod sursa (job #1634297) | Cod sursa (job #1702622) | Cod sursa (job #840209) | Cod sursa (job #2623579) | Cod sursa (job #3264378)
#include <bits/stdc++.h>
#define cin fin
#define cout fout
using namespace std;
ifstream fin("barbar.in");
ofstream fout("barbar.out");
const int NMAX=1001;
int numRows, numCols;
int dragonDistance[NMAX+1][NMAX+1], minDistance[NMAX+1][NMAX+1];
char labyrinth[NMAX+1][NMAX+1];
char line[NMAX+1];
int dX[] = {0, 0, 1, -1};
int dY[] = {-1, 1, 0, 0};
queue<pair<int, int>> q;
bool isWithinMatrix(int x, int y) {
return x > 0 && x <= numRows && y > 0 && y <= numCols;
}
void calculateDragonDistances() {
while (!q.empty()) {
int row = q.front().first;
int col = q.front().second;
q.pop();
for (int k = 0; k < 4; ++k) {
int newX = row + dX[k];
int newY = col + dY[k];
if (isWithinMatrix(newX, newY) && labyrinth[newX][newY] != '*' && dragonDistance[newX][newY] == 2e9) {
dragonDistance[newX][newY] = dragonDistance[row][col] + 1;
q.push({newX, newY});
}
}
}
}
void bfs() {
while (!q.empty()) {
int row = q.front().first;
int col = q.front().second;
q.pop();
for (int k = 0; k < 4; ++k) {
int newX = row + dX[k];
int newY = col + dY[k];
if (isWithinMatrix(newX, newY) && labyrinth[newX][newY] != '*' && minDistance[newX][newY] < min(minDistance[row][col], dragonDistance[newX][newY])) {
minDistance[newX][newY] = min(minDistance[row][col], dragonDistance[newX][newY]);
q.push({newX, newY});
}
}
}
}
int main() {
cin >> numRows >> numCols;
int startX, startY, endX, endY;
for (int i = 1; i <= numRows; ++i) {
cin >> line;
for (int j = 1; j <= numCols; ++j) {
labyrinth[i][j] = line[j - 1];
dragonDistance[i][j] = 2e9;
minDistance[i][j] = -1;
if (labyrinth[i][j] == 'D') {
dragonDistance[i][j] = 0;
q.push({i, j});
} else if (labyrinth[i][j] == 'I') {
startX = i;
startY = j;
} else if (labyrinth[i][j] == 'O') {
endX = i;
endY = j;
}
}
}
calculateDragonDistances();
minDistance[startX][startY] = dragonDistance[startX][startY];
q.push({startX, startY});
bfs();
cout << minDistance[endX][endY];
return 0;
}