Pagini recente » Cod sursa (job #1834126) | Cod sursa (job #2916699) | Cod sursa (job #841873) | Cod sursa (job #1506954) | Cod sursa (job #2892728)
#include <iostream>
#include <fstream>
#include <queue>
#include <climits>
using namespace std;
const int dim = 1e3 + 5;
char a[dim][dim];
int dist[dim][dim], ddist[dim][dim];
int n, m;
struct Celula{
int lin, col;
}start, finish;
queue <Celula> Q;
bool isValid(Celula cell){
return (cell.lin >= 1 and cell.lin <= n and cell.col >= 1 and cell.col <= m and a[cell.lin][cell.col] != '*' and a[cell.lin][cell.col] != 'D');
}
void Lee(){
for(int i = 1; i <= n; i++){
for(int j = 1; j <= m; j++){
if(a[i][j] == 'I' or a[i][j] == 'O' or a[i][j] == '.'){
dist[i][j] = INT_MAX;
}
if(a[i][j] == 'D'){
Q.push({i, j});
}
}
}
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 neigh = {cell.lin + dx[dir], cell.col + dy[dir]};
if(isValid(neigh) and dist[neigh.lin][neigh.col] > dist[cell.lin][cell.col] + 1){
dist[neigh.lin][neigh.col] = dist[cell.lin][cell.col] + 1;
Q.push(neigh);
}
}
}
}
bool Verify(int x){
const int dx[] = {-1, 0, 1, 0};
const int dy[] = {0, -1, 0, 1};
for(int i = 1; i <= n; i++){
for(int j = 1; j <= m; j++){
ddist[i][j] = INT_MAX;
}
}
Q.push(start);
ddist[start.lin][start.col] = 0;
while(!Q.empty()){
Celula cell = Q.front();
Q.pop();
for(int dir = 0; dir < 4; dir++){
Celula neigh = {cell.lin + dx[dir], cell.col + dy[dir]};
if(isValid(neigh) and ddist[neigh.lin][neigh.col] > ddist[cell.lin][cell.col] + 1 and dist[neigh.lin][neigh.col] >= x){
ddist[neigh.lin][neigh.col] = ddist[cell.lin][cell.col] + 1;
Q.push(neigh);
}
}
}
if(ddist[finish.lin][finish.col] != INT_MAX){
return 1;
}
return 0;
}
int main(){
ifstream cin("barbar.in");
ofstream cout("barbar.out");
cin >> n >> m;
for(int i = 1; i <= n; i++){
for(int j = 1; j <= m; j++){
cin >> a[i][j];
if(a[i][j] == 'I'){
start = {i, j};
}
if(a[i][j] == 'O'){
finish = {i, j};
}
}
}
Lee();
int sol = 0, left = 1, right = dist[start.lin][start.col];
while(left <= right){
int mid = (left + right) / 2;
if(Verify(mid)){
sol = mid;
left = mid + 1;
}
else{
right = mid - 1;
}
}
cout << sol;
return 0;
}