Pagini recente » Cod sursa (job #2139616) | Cod sursa (job #618474) | Cod sursa (job #684451) | Cod sursa (job #727784) | Cod sursa (job #2420707)
#include <bits/stdc++.h>
#define FOR(a, b) for(int i = a; i <= b; ++i)
using namespace std;
ifstream in("barbar.in");
ofstream out("barbar.out");
const int MX_SZ = 1005;
const int INF = 1<<30;
const int DX[4] = {-1, 0, 1, 0};
const int DY[4] = { 0, 1, 0, -1};
struct xy{
int x,y;
};
int N,M,d[MX_SZ][MX_SZ],l=INF,r,ans;
char m[MX_SZ][MX_SZ];
xy st, en;
queue <xy> q,q1;
bitset <MX_SZ> bs[MX_SZ];
inline bool inside(const xy &p){
return p.x >= 1 && p.x <= N && p.y >= 1 && p.y <= M;
}
void reset(){
for(int i = 1; i <= N; ++i)
for(int j = 1; j <= M; ++j)
bs[i][j] = 0;
}
void read(){
in>>N>>M;
for(int i = 1; i <= N; ++i)
in>>(m[i]+1);
for(int i = 1; i <= N; ++i)
for(int j = 1; j <= M; ++j)
d[i][j] = INF;
}
bool bfs(const int &p){
reset();
q.push(st);
bs[st.x][st.y] = 1;
if(d[st.x][st.y] < p) return 0;
while(!q.empty()){
xy f = q.front();
q.pop();
for(int i = 0; i < 4; ++i){
xy nx = {f.x + DX[i], f.y + DY[i]};
if(inside(nx) && (m[nx.x][nx.y] == '.' || m[nx.x][nx.y] == 'O') && d[nx.x][nx.y] >= p && bs[nx.x][nx.y] == 0){
bs[nx.x][nx.y] = 1;
q.push(nx);
}
}
}
return bs[en.x][en.y] == 1 ? 1 : 0;
}
int main(){
ios::sync_with_stdio(0);
read();
for(int i = 1; i <= N; ++i)
for(int j = 1; j <= M; ++j)
if(m[i][j] == 'I') st = {i, j};
else if(m[i][j] == 'D') q1.push({i, j}), d[i][j] = 0;
else if(m[i][j] == 'O') en = {i, j};
while(!q1.empty()){
xy f = q1.front();
q1.pop();
for(int i = 0; i < 4; ++i){
xy nx = {f.x + DX[i], f.y + DY[i]};
if(inside(nx) && d[nx.x][nx.y] > d[f.x][f.y] + 1 && m[nx.x][nx.y] != '*'){
d[nx.x][nx.y] = d[f.x][f.y] + 1;
r = max(r, d[nx.x][nx.y]);
l = min(l, d[nx.x][nx.y]);
q1.push(nx);
}
}
}
q1.push(st);
bs[st.x][st.y] = 1;
while(!q1.empty()){
xy f = q1.front();
q1.pop();
for(int i = 0; i < 4; ++i){
xy nx = {f.x + DX[i], f.y + DY[i]};
if(inside(nx) && bs[nx.x][nx.y] == 0 && (m[nx.x][nx.y] == '.' || m[nx.x][nx.y] == 'O')){
bs[nx.x][nx.y] = 1;
q1.push(nx);
if(m[nx.x][nx.y] == 'O'){
break;
break;
}
}
}
}
if(bs[en.x][en.y] == 0){
out<<-1;
return 0;
}
while(l <= r){
int m = (l + r) / 2;
if(bfs(m)){
ans = max(ans, m);
++l;
}
else{
--r;
}
}
out<<ans;
return 0;
}