Pagini recente » Cod sursa (job #2812270) | Cod sursa (job #2917925) | Cod sursa (job #2703452) | Cod sursa (job #2094119) | Cod sursa (job #3262821)
#include <bits/stdc++.h>
#define cin fin
#define cout fout
using namespace std;
ifstream cin("barbar.in");
ofstream cout("barbar.out");
int n, m, D[1002][1002], Min[1002][1002];
char M[1002][1002];
int dx[] = {0, 0, 1, -1};
int dy[] = {-1, 1, 0, 0};
queue <pair<int, int> > Q;
bool inMatrix(int x, int y) {
return x > 0 && x <= n && y > 0 && y <= m;
}
void LeeDistDrag() {
while(!Q.empty()) {
int l = Q.front().first;
int c = Q.front().second;
Q.pop();
for(int k = 0; k < 4; ++k) {
int x = l + dx[k];
int y = c + dy[k];
if(inMatrix(x, y) && M[x][y] != '*' && D[x][y] == 2e9) {
D[x][y] = D[l][c] + 1;
Q.push({x, y});
}
}
}
}
void lee() {
while(!Q.empty()) {
int l = Q.front().first;
int c = Q.front().second;
Q.pop();
for(int k = 0; k < 4; ++k) {
int x = l + dx[k];
int y = c + dy[k];
if(inMatrix(x, y) && M[x][y] != '*' && Min[x][y] < min(Min[l][c], D[x][y])) {
Min[x][y] = min(Min[l][c], D[x][y]);
Q.push({x, y});
}
}
}
}
int main()
{
cin >> n >> m;
int x, y, xx, yy;
for(int i = 1; i <= n; ++i) {
cin >> (M[i] + 1);
for(int j = 1; j <= m; ++j) {
D[i][j] = 2e9;
Min[i][j] = -1;
if(M[i][j] == 'D') {
D[i][j] = 0;
Q.push({i, j});
}
else if(M[i][j] == 'I') {
x = i;
y = j;
}
else if(M[i][j] == 'O') {
xx = i;
yy = j;
}
}
}
LeeDistDrag();
Min[x][y] = D[x][y];
Q.push({x, y});
lee();
cout << Min[xx][yy];
return 0;
}