Pagini recente » Cod sursa (job #1503278) | Cod sursa (job #2795141) | Cod sursa (job #11185) | Cod sursa (job #1129306) | Cod sursa (job #2813245)
#include <fstream>
#include <queue>
#include <bitset>
using namespace std;
const int DIM = 1005;
int n, m, dist[DIM][DIM];
bitset<1> viz[DIM][DIM];
bitset<1> wall[DIM][DIM];
//char a[DIM][DIM];
struct Celula {
int lin, col;
};
bool isEqual(Celula a,Celula b)
{
return a.col == b.col and a.lin == b.lin ;
}
bool isInside(Celula cell)
{
return (cell.lin >= 1 && cell.lin <= n && cell.col >= 1 && cell.col <= m);
}
bool isWall(Celula cell)
{
return wall[cell.lin][cell.col] == 1;//'*';
}
bool isVisited(Celula cell)
{
return viz[cell.lin][cell.col]==1;
}
bool isValid(Celula cell) {
return (isInside(cell) && !isWall(cell) && !isVisited(cell));
}
bool isValidAndDistant(Celula cell, int D) {
return (isInside(cell) && !isWall(cell) && !isVisited(cell) && dist[cell.lin][cell.col] >= D);
}
queue<Celula> Q;
Celula start, finish;
/// extended Lee ( multiple sources )
/// calculate danger distance
void Lee_DangerDistance() {
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;
viz[neighbor.lin][neighbor.col] = true;
Q.push(neighbor);
}
}
}
}
bool Lee_SearchMinDistance(int minDistanceDanger) {
const int dx[] = {-1, 0, 1, 0};
const int dy[] = { 0, 1, 0, -1};
if(dist[start.lin][start.col] < minDistanceDanger) {
return false;
}
while(!Q.empty()) {
Q.pop();
}
///classic Lee
Q.push(start);
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
viz[i][j] = false;
}
}
viz[start.lin][start.col] = true;
while(!Q.empty()) {
Celula cell = Q.front();
Q.pop();
if(isEqual(cell,finish)) {
return true;
}
for(int dir = 0; dir < 4; dir++) {
Celula neighbor = {cell.lin + dx[dir], cell.col + dy[dir]};
if(isValidAndDistant(neighbor, minDistanceDanger)) {
viz[neighbor.lin][neighbor.col] = true;
Q.push(neighbor);
}
}
}
return false;
}
int main() {
ifstream fin("barbar.in");
ofstream fout("barbar.out");
fin >> n >> m;
string s;
for(int i = 0; i < n; i++) {
fin >> s;//(a[i] + 1);
for(int j = 0; j < m; j++) {
//viz[i][j] = false;
//dist[i][j] = -1;
if(s[j] == 'I') {
start = {i, j};
}
else if(s[j] == 'O') {
finish = {i, j};
}
else if(s[j] == '*') {
wall[i][j] = true;
}
else if(s[j] == 'D') {
dist[i][j] = 0;
viz[i][j] = true;
Q.push({i, j});
}
}
}
Lee_DangerDistance();
int st = 1, dr = n * m, sol = -1;
while(st <= dr) {
int mij = (st + dr) / 2;
if(Lee_SearchMinDistance(mij)) {
sol = mij; st = mij + 1;
}
else {
dr = mij - 1;
}
}
fout << sol << "\n";
return 0;
}