Pagini recente » Cod sursa (job #3323910) | Cod sursa (job #3340930) | Borderou de evaluare (job #3321190) | Cod sursa (job #3319962) | Cod sursa (job #3341309)
#include "bits/stdc++.h"
#define pii std :: pair < int, int >
const int NMAX = 1000;
int dx[] = {0, 0, -1, 1};
int dy[] = {-1, 1, 0, 0};
int n, m, dist[NMAX + 5][NMAX + 5], x_start, y_start, x_stop, y_stop, maxx, sol;
int d[NMAX + 5][NMAX + 5];
char mat[NMAX + 5][NMAX + 5];
bool InMat(int i, int j){
if(i >= 1 and i <= n and j >= 1 and j <= m){
return true;
}
return false;
}
std :: queue < pii > q;
void BFS_Dragons(){
while(!q.empty()){
pii node = q.front();
q.pop();
for(int k = 0; k < 4; k++){
int new_line = node.first + dx[k];
int new_column = node.second + dy[k];
if(InMat(new_line, new_column) and dist[new_line][new_column] == -1 and (mat[new_line][new_column] == '.' or mat[new_line][new_column] == 'O')){
dist[new_line][new_column] = dist[node.first][node.second] + 1;
q.push({new_line, new_column});
}
}
}
}
bool Check(int x){
for(int i = 1; i <= n; i++){
for(int j = 1; j <= m; j++){
d[i][j] = -1;
}
}
while(!q.empty()){
q.pop();
}
q.push({x_start, y_start});
while(!q.empty()){
auto node = q.front();
q.pop();
for(int k = 0; k < 4; k++){
int new_line = node.first + dx[k], new_column = node.second + dy[k];
if(new_line == x_stop and new_column == y_stop){
return true;
}
if(InMat(new_line, new_column) and d[new_line][new_column] == -1 and dist[new_line][new_column] >= x){
d[new_line][new_column] = d[node.first][node.second] + 1;
q.push({new_line, new_column});
}
}
}
return false;
}
void Solve(){
std :: cin >> n >> m;
for(int i = 1; i <= n; i++){
for(int j = 1; j <= m; j++){
dist[i][j] = -1;
}
}
for(int i = 1; i <= n; i++){
for(int j = 1; j <= m; j++){
std :: cin >> mat[i][j];
if(mat[i][j] == 'D'){
dist[i][j] = 0;
q.push({i, j});
}else if(mat[i][j] == 'O'){
x_stop = i, y_stop = j;
}else if(mat[i][j] == 'I'){
x_start = i, y_start = j;
}
}
}
BFS_Dragons();
for(int i = 1; i <= n; i++){
for(int j = 1; j <= m; j++){
maxx = std :: max(dist[i][j], maxx);
}
//std :: cout << '\n';
}
//std :: cout << Check(2) << '\n';
int left = 0, right = maxx;
while(left <= right){
int mid = (left + right) >> 1;
if(Check(mid)){
left = mid + 1;
sol = mid;
}else{
right = mid - 1;
}
}
std :: cout << sol;
}
signed main(){
std :: ios_base :: sync_with_stdio(false);
std :: cin.tie(nullptr);
freopen("barbar.in", "r", stdin);
freopen("barbar.out", "w", stdout);
Solve();
return 0;
}