Pagini recente » Cod sursa (job #3352630) | Cod sursa (job #117547) | Cod sursa (job #683678) | Cod sursa (job #790515) | Cod sursa (job #3334237)
#include <bits/stdc++.h>
#define int long long
#pragma GCC optimize ("O3")
#define pb push_back
using namespace std;
#define f first
#define s second
int n, m;
int dx[]={1, -1, 0, 0, 0, 0};
int dy[]={0, 0, 1, -1, 0, 0};
int dz[]={0, 0, 0, 0, -1, 1};
struct cat{
int x , y , z;
};
bool inmatt(cat a){
if(1 <= a.x && a.x <= n && 1 <= a.y && a.y <= n && 1 <= a.z && a.z <= n)return true;
return false;
}
bool inmat(int x, int y){
if(1 <= x && x <= n && 1 <= y && y <= m)return true;
return false;
}
signed main(){
ifstream cin ("barbar.in");
ofstream cout ("barbar.out");
cin >> n >> m;
vector < vector <int>> a(n + 2, vector<int>(m + 2, 1e9));
vector <pair <int, int>> st;
int s1, s2, e1, e2;
for(int i=1;i <= n;i++){
for(int j=1;j <= m;j++){
char x;cin >> x;
if(x == '*')a[i][j]=-1;
else if(x == 'D'){
st.pb({i , j});
}else if(x == 'I'){
s1=i, s2=j;
}else if(x == 'O'){
e1=i; e2=j;
}
}
}
queue<pair <int, int>> q;
for(auto [x, y] : st){
q.push({x, y});
a[x][y]=0;
}
while(!q.empty()){
int x=q.front().f, y=q.front().s;
q.pop();
for(int d=0;d < 4;d++){
int nx=x + dx[d];
int ny=y + dy[d];
if(inmat(nx, ny) && a[nx][ny] != -1){
if(a[nx][ny] > a[x][y] + 1){
a[nx][ny]=a[x][y] + 1;
q.push({nx, ny});
}
}
}
}
int l=0, r=n + m;
while(l + 1 < r){
int mid=(l + r) / 2;
int ok=true;
if(a[s1][s2] < mid)ok=false;
vector <vector <int>> vis(n + 2, vector <int> (m + 2, 0));
q.push({s1, s2});
while(!q.empty()){
int x=q.front().f, y=q.front().s;
q.pop();
if(vis[x][y] == 1)continue;
if(a[x][y] < mid)continue;
vis[x][y]=1;
for(int d=0;d < 4;d++){
int nx=x + dx[d];
int ny=y + dy[d];
if(inmat(nx, ny) && a[nx][ny] != -1)q.push({nx, ny});
}
}
if(vis[e1][e2] == 1)l = mid;
else r = mid;
}
if(a[e1][e2] == 1e9 || l == 0)cout << "-1";
else cout << l;
}