Pagini recente » Cod sursa (job #1554533) | Cod sursa (job #2340217) | Cod sursa (job #2255192) | Cod sursa (job #1590084) | Cod sursa (job #2809314)
#include <fstream>
#include <queue>
using namespace std;
const int Nmax = 1005;
int n, m, dist[Nmax][Nmax];
bool viz[Nmax][Nmax];
char a[Nmax][Nmax];
struct Celula {
int lin, col;
const bool operator == (const Celula x) {
return lin == x.lin && col == x.col;
}
};
queue<Celula> Q;
Celula start, finish;
bool isValid(Celula cell) {
return (cell.lin >= 1 && cell.lin <= n && cell.col >= 1 && cell.col <= m &&
a[cell.lin][cell.col] != '*' && dist[cell.lin][cell.col] == -1);
}
bool isValid1(Celula cell, int D) {
return (cell.lin >= 1 && cell.lin <= n && cell.col >= 1 && cell.col <= m &&
a[cell.lin][cell.col] != '*' && !viz[cell.lin][cell.col] && dist[cell.lin][cell.col] >= D);
}
void Lee_Extins() {
const int dx[] = {-1, 0, 1, 0};
const int dy[] = { 0, 1, 0, -1};
while(!Q.empty()) {
Celula cell = Q.front();
Q.pop();
for(int dir = 0; dir < 4; dir++) {
Celula neighbor = {cell.lin + dx[dir], cell.col + dy[dir]};
if(isValid(neighbor)) {
dist[neighbor.lin][neighbor.col] = dist[cell.lin][cell.col] + 1;
Q.push(neighbor);
}
}
}
}
bool Ok(int D) {
const int dx[] = {-1, 0, 1, 0};
const int dy[] = { 0, 1, 0, -1};
while(!Q.empty()) {
Q.pop();
}
Q.push(start);
for(int i = 1; i <= n; i++) {
for(int j = 1; j <= m; j++) {
viz[i][j] = false;
}
}
viz[start.lin][start.col] = true;
while(!Q.empty()) {
Celula cell = Q.front();
Q.pop();
if(cell == finish) {
return true;
}
for(int dir = 0; dir < 4; dir++) {
Celula neighbor = {cell.lin + dx[dir], cell.col + dy[dir]};
if(isValid1(neighbor, D)) {
viz[neighbor.lin][neighbor.col] = true;
Q.push(neighbor);
}
}
}
return false;
}
int main() {
ifstream fin("barbar.in");
ofstream fout("barbar.out");
fin >> n >> m;
for(int i = 1; i <= n; i++) {
fin >> (a[i] + 1);
for(int j = 1; j <= m; j++) {
dist[i][j] = -1;
if(a[i][j] == 'I') {
start = {i, j};
}
else if(a[i][j] == 'O') {
finish = {i, j};
}
else if(a[i][j] == 'D') {
dist[i][j] = 0;
Q.push({i, j});
}
}
}
Lee_Extins();
int st = 1, dr = n * m, sol = -1;
while(st <= dr) {
int mij = (st + dr) / 2;
if(Ok(mij)) {
sol = mij; st = mij + 1;
}
else {
dr = mij - 1;
}
}
fout << sol << "\n";
return 0;
}