Pagini recente » Cod sursa (job #1341147) | Cod sursa (job #2159561) | Cod sursa (job #2632301) | Cod sursa (job #2897266) | Cod sursa (job #2552529)
#include <fstream>
#include <queue>
using namespace std;
ifstream cin ("barbar.in");
ofstream cout ("barbar.out");
int n, m;
pair <int, int> a, b;
queue <pair <int, int>> q;
char v[1005][1005];
bool viz[1005][1005];
int dist[1005][1005], dp[1005][1005];
int dx[] = {-1, 0, 1, 0};
int dy[] = {0, 1, 0, -1};
bool check(int val) {
q.push({a.first, a.second});
for(int i = 1; i <= n; i++) {
for(int j = 1; j <= m; j++)
viz[i][j] = 0;
}
if(dist[a.first][a.second] < val)
return 0;
viz[a.first][a.second] = 1;
while(!q.empty()) {
pair <int, int> nod = q.front();
q.pop();
for(int i = 0; i < 4; i++) {
int x = nod.first + dx[i], y = nod.second + dy[i];
if(v[x][y] != '*' && 1 <= x && x <= n && 1 <= y && y <= m && !viz[x][y] && dist[x][y] >= val)
q.push({x, y}), viz[x][y] = 1;
}
}
return viz[b.first][b.second];
}
int main() {
cin >> n >> m;
for(int i = 1; i <= n; i++) {
cin >> (v[i] + 1);
for(int j = 1; j <= m; j++) {
if(v[i][j] == 'D')
q.push({i, j}), dist[i][j] = 0;
else
dist[i][j] = n * m + 5;
}
}
while(!q.empty()) {
pair <int, int> nod = q.front();
q.pop();
for(int i = 0; i < 4; i++) {
int x = nod.first + dx[i], y = nod.second + dy[i];
if(v[x][y] != '*' && 1 <= x && x <= n && 1 <= y && y <= m && dist[x][y] > dist[nod.first][nod.second] + 1) {
dist[x][y] = dist[nod.first][nod.second] + 1;
q.push({x, y});
}
}
}
for(int i = 1; i <= n; i++) {
for(int j = 1; j <= m; j++) {
dist[i][j] = (dist[i][j] == n * m + 5 ? 0 : dist[i][j]);
if(v[i][j] == 'I')
a = {i, j};
if(v[i][j] == 'O')
b = {i, j};
}
}
int st = 1, dr = n + m, mid;
while(st <= dr) {
mid = (st + dr) >> 1;
if(!check(mid))
dr = mid - 1;
else
st = mid + 1;
}
if(dr)
cout << dr;
else
cout << -1;
return 0;
}