Pagini recente » Cod sursa (job #1764255) | Cod sursa (job #2828113) | Cod sursa (job #2503428) | Cod sursa (job #2087280) | Cod sursa (job #2785085)
#include <bits/stdc++.h>
using namespace std;
inline void Open(const string Name) {
#ifndef ONLINE_JUDGE
(void)!freopen((Name + ".in").c_str(), "r", stdin);
(void)!freopen((Name + ".out").c_str(), "w", stdout);
#endif
}
const int l[] = {-1, 1, 0, 0}, c[] = {0, 0, -1, 1};
queue <array <int, 2>> q;
char ch;
int a[1002][1002], b[1002][1002];
int N, M, xi, yi, xf, yf, dist;
void bfs() {
while(!q.empty()) {
int i = q.front()[0], j = q.front()[1];
q.pop();
for(int d = 0;d < 4;d++) {
int ii = i + l[d], jj = j + c[d];
if(a[ii][jj] == 0) {
a[ii][jj] = a[i][j] + 1;
q.push({ii, jj});
}
}
}
}
void dfs(int i, int j) {
b[i][j] = 1;
for(int d = 0;d < 4;d++) {
int ii = i + l[d], jj = j + c[d];
if(b[ii][jj] == 0 && a[ii][jj] != -1 && a[ii][jj] > dist)
dfs(ii, jj);
}
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
Open("barbar");
cin >> N >> M;
for(int i = 0;i <= N + 1;i++)
a[i][0] = a[i][M + 1] = -1;
for(int i = 0;i <= M + 1;i++)
a[0][i] = a[N + 1][i] = -1;
for(int i = 1;i <= N;i++)
for(int j = 1;j <= M;j++) {
cin >> ch;
if(ch == 'I')
xi = i, yi = j;
if(ch == 'O')
xf = i, yf = j;
if(ch == '*')
a[i][j] = -1;
if(ch == 'D')
a[i][j] = 1, q.push({i, j});
}
bfs();
int l = 1, r = a[xi][yi], ans = -1;
while(l <= r) {
int m = (l + r) / 2;
memset(b, 0, sizeof(b));
dist = m;
dfs(xi, yi);
if(b[xf][yf] == 1) {
ans = m;
l = m + 1;
} else {
r = m - 1;
}
}
cout << ans;
return 0;
}