Pagini recente » Cod sursa (job #2669434) | Cod sursa (job #2314224) | Cod sursa (job #2939627) | Cod sursa (job #362200) | Cod sursa (job #2957375)
#include <iostream>
#include <fstream>
#include <deque>
#include <cstring>
#define pii pair<int, int>
#define MAX 1002
using namespace std;
int n,m,dist[MAX][MAX],v[MAX][MAX],vf[MAX][MAX];
char ch;
pii loc,com;
ifstream fin("barbar.in");
ofstream fout("barbar.out");
int dx[] = {-1,1,0,0};
int dy[] = {0,0,-1,1};
bool inauntru(int x, int y){
return ((1 <= x && x <= n) && (1 <= y && y <= m));
}
bool check(int maxi){
for(int i = 1; i <= n; i++){
memset(vf[i], 0, sizeof(vf[i]));
}
deque<pii> cd;
cd.push_back(loc);
vf[loc.first][loc.second] = 1;
while(!cd.empty()){
auto [x, y] = cd.back();
for(int k = 0; k < 4; k++){
int xnou = x+dx[k];
int ynou = y+dy[k];
if(inauntru(xnou, ynou) && vf[xnou][ynou] == 0 && v[xnou][ynou] == 0 && maxi <= dist[xnou][ynou]){
if(xnou == com.first && ynou == com.second){
return true;
}
vf[xnou][ynou] = 1;
cd.push_front({xnou, ynou});
}
}
cd.pop_back();
}
return false;
}
int main()
{
deque<pii> cd;
fin >> n >> m;
for(int i = 1; i <= n; i++){
for(int j = 1; j <= m; j++){
fin >> ch;
if(ch == 'D'){
cd.push_back({i, j});
dist[i][j] = 1;
}else if(ch == 'I'){
loc = {i, j};
}else if(ch == '*'){
v[i][j] = 1;
}else if(ch == 'O'){
com = {i, j};
}
}
}
while(!cd.empty()){
auto [x, y] = cd.back();
for(int k = 0; k < 4; k++){
int xnou = x+dx[k];
int ynou = y+dy[k];
if(inauntru(xnou, ynou) && dist[xnou][ynou] == 0 && v[xnou][ynou] == 0){
dist[xnou][ynou] = 1+dist[x][y];
cd.push_front({xnou, ynou});
}
}
cd.pop_back();
}
int ans = -1, st = 2, dr = n*m;
while(st <= dr){
int mid = (st+dr)/2;
if(check(mid)){
ans = mid;
st = mid+1;
}else{
dr = mid-1;
}
}
if(ans != -1){
fout << ans-1;
}else{
fout << -1;
}
return 0;
}