Pagini recente » Cod sursa (job #1093539) | Cod sursa (job #2067032) | Cod sursa (job #2404048) | Cod sursa (job #643034) | Cod sursa (job #912043)
Cod sursa(job #912043)
#include <fstream>
#include <queue>
using namespace std;
ifstream f("barbar.in");
ofstream g("barbar.out");
const int MAX_N = 1005;
const int INF = (1 << 30);
const int dx[4] = {-1, 0, 1, 0};
const int dy[4] = {0, 1, 0, -1};
int n, m, pozl, pozc, iesireX, iesireY, D[MAX_N][MAX_N], rez[MAX_N][MAX_N];
char A[MAX_N][MAX_N];
queue < pair<int, int> > Q;
void read() {
string s;
f >> n >> m;
for (int i = 1; i <= n; i++) {
f >> s;
for (int j = 0; j < m; j++) {
A[i][j + 1] = s[j];
if (s[j] == 'D') {
Q.push (make_pair(i, j + 1));
D[i][j + 1] = 0;
} else if (s[j] == 'I') {
pozl = i;
pozc = j + 1;
} else if (s[j] == 'O') {
iesireX = i;
iesireY = j + 1;
}
}
}
}
void init() {
for (int i = 1; i <= 1000; i++)
for (int j = 1; j <= 1000; j++) {
D[i][j] = INF;
rez[i][j] = -1;
}
}
int conditie(int l, int c) {
if (l >= 1 && l <= n && c >= 1 && c <= m && A[l][c] != '*')
return 1;
return 0;
}
void lee() {
while (!Q.empty()) {
pair <int, int> X = Q.front(); Q.pop();
for (int k = 0; k < 4; k++) {
if (D[X.first][X.second] + 1 < D[X.first + dx[k]][X.second + dy[k]] && conditie(X.first + dx[k], X.second + dy[k])) {
D[X.first + dx[k]][X.second + dy[k]] = D[X.first][X.second] + 1;
Q.push (make_pair(X.first + dx[k], X.second + dy[k]));
}
}
}
}
void lee_sukar() {
rez[pozl][pozc] = D[pozl][pozc];
Q.push (make_pair(pozl, pozc));
while (!Q.empty()) {
pair <int, int> X = Q.front(); Q.pop();
for (int k = 0; k < 4; k++) {
int l = X.first + dx[k];
int c = X.second + dy[k];
if (rez[l][c] == -1 && conditie(l, c)) {
rez[l][c] = min(rez[X.first][X.second], D[l][c]);
Q.push (make_pair(l, c));
} else if (rez[X.first][X.second] > rez[l][c] && min(rez[X.first][X.second], D[l][c]) > rez[l][c] && conditie(l, c)) {
rez[l][c] = min(rez[X.first][X.second], D[l][c]);
Q.push (make_pair(l, c));
}
}
}
}
void write(int M[MAX_N][MAX_N]) {
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++)
g << M[i][j] << " ";
g << '\n';
}
}
int main() {
init();
read();
lee();
lee_sukar();
g << rez[iesireX][iesireY] << '\n';
f.close();
g.close();
return 0;
}