Pagini recente » Cod sursa (job #2374383) | Cod sursa (job #73176) | Cod sursa (job #2568224) | Cod sursa (job #476247) | Cod sursa (job #1658504)
#include <fstream>
#include <queue>
using namespace std;
typedef pair<int,int> PL;
const int dirx[] = {0,1,0,-1};
const int diry[] = {1,0,-1,0};
ifstream cin("barbar.in");
ofstream cout("barbar.out");
int N, M, dist[1002][1002], MA[1002][1002], d2[1002][1002], ix, iy, jx, jy;
bool viz[1002][1002];
queue<PL> QUEUE;
queue<PL> rs;
void Lee1(){
for(int i = 0; i < N; i++)
for(int j = 0; j < M; j++)
if(MA[i][j] == 1){
QUEUE.push(make_pair(i,j));
viz[i][j] = 1;
}
while(!QUEUE.empty()){
PL node = QUEUE.front();
QUEUE.pop();
for(int i = 0; i < 4; i++){
int x = node.first + dirx[i];
int y = node.second + diry[i];
if(viz[x][y] == 0 && x >= 0 && x < N && y < M && y >= 0 && (MA[x][y] == 0 || MA[x][y] == -2 || MA[x][y] == -1)){
viz[x][y] = 1;
QUEUE.push(make_pair(x,y));
dist[x][y] = dist[node.first][node.second]+1;
}
}
}
}
bool check(int mid){
for(int i = 0; i < N; i++)
for(int j = 0; j < M; j++)
viz[i][j] = 0, d2[i][j] = 0;
while(!rs.empty()) rs.pop();
rs.push(make_pair(jx, jy));
viz[jx][jy] = 1;
int xi, yi;
while(!rs.empty()){
PL node = rs.front();
rs.pop();
for(int i = 0; i < 4; i++){
xi = node.first + dirx[i];
yi = node.second + diry[i];
if(viz[xi][yi] == 0 && xi >= 0 && xi < N && yi >= 0 && yi < M && dist[xi][yi] >= mid && (MA[xi][yi] == 0 || MA[xi][yi] == -2 || MA[xi][yi] == -1)){
viz[xi][yi] = 1;
rs.push(make_pair(xi,yi));
d2[xi][yi] = d2[node.first][node.second] + 1;
}
}
}
if(viz[ix][iy]) return 1;
return 0;
}
char x;
int main(){
cin >> N >> M;
for(int i = 0; i < N; i++)
for(int j = 0; j < M; j++){
cin >> x;
if(x == 'I'){ MA[i][j] = -1; jx = i; jy = j;}// Intrare: -1
if(x == 'O'){ MA[i][j] = -2; ix = i; iy = j;}// Iesire: -2
if(x == 'D') MA[i][j] = 1; // Dragon: 1
if(x == '*') MA[i][j] = 2; // Perete: 2
}
Lee1();
/*for(int i = 0; i < N; i++){
for(int j = 0; j < M; j++) cout << MA[i][j] << " ";
cout << '\n';
}*/
/*for(int i = 0; i < N; i++){
for(int j = 0; j < M; j++) cout << dist[i][j] << " ";
cout << '\n';
}
cout << '\n';*/
int step = 1024,i;
for(i = 0; step; step >>= 1)
if(check(i+step)) i+=step;
if(!i) cout << -1;
else cout << i;
/*for(int i = 0; i < N; i++){
for(int j = 0; j < M; j++) cout << d2[i][j] << " ";
cout << '\n';
}*/
return 0;
}