Pagini recente » Cod sursa (job #3237226) | Cod sursa (job #37123) | Cod sursa (job #1970102) | Cod sursa (job #1101589) | Cod sursa (job #2700026)
#include <bits/stdc++.h>
#define ll long long
#define sz(x) (int)(x).size()
#define debug(v,n) for (int i = 1; i <= (n); ++i) cout << v[i] << " ";
#define next cout << '\n'
using namespace std;
const int N = 1005;
int n, m, ans;
char mt[N][N];
int dp[N][N];
bool in[N][N];
pair<int, int> x, y, dragon;
int dl[4] = {0, 1, 0, -1};
int dc[4] = {1, 0, -1, 0};
struct cmp {
bool operator()(pair<int,int> a, pair<int,int> b) {
return dp[a.first][a.second] < dp[b.first][b.second];
}
};
priority_queue<pair<int,int>, vector<pair<int,int>>, cmp> q;
void bfs(int i, int j) {
q.push({i, j});
while(!q.empty()) {
i = q.top().first;
j = q.top().second;
q.pop();
for (int d = 0; d < 4; ++d) {
if(mt[i + dl[d]][j + dc[d]] == '.') {
dp[i + dl[d]][j + dc[d]] = min(dp[i][j], dp[i + dl[d]][j + dc[d]]);
if(in[i + dl[d]][j + dc[d]] == false) {
q.push({i + dl[d], j + dc[d]});
in[i + dl[d]][j + dc[d]] = true;
}
}
}
}
}
int main() {
//ifstream fin("date.in.txt");
ifstream fin("barbar.in");
ofstream fout("barbar.out");
fin >> n >> m;
for (int i = 1; i <= n; ++i) {
for (int j = 1; j <= m; ++j) {
fin >> mt[i][j];
if(mt[i][j] == 'D')
dragon = {i, j};
else if(mt[i][j] == 'I') {
x = {i, j};
mt[i][j] = '.';
}
else if(mt[i][j] == 'O') {
y = {i, j};
mt[i][j] = '.';
}
dp[i][j] = INT_MAX;
}
}
queue<pair<int,int>> coada;
coada.push({dragon.first, dragon.second});
dp[dragon.first][dragon.second] = 0;
while(!coada.empty()) {
int i = coada.front().first;
int j = coada.front().second;
coada.pop();
in[i][j] = false;
for (int d = 0; d < 4; ++d) {
if(mt[i + dl[d]][j + dc[d]] == 'D') {
dp[i + dl[d]][j + dc[d]] = 0;
if(in[i + dl[d]][j + dc[d]] == false) {
coada.push({i + dl[d], j + dc[d]});
in[i + dl[d]][j + dc[d]] = true;
}
}
else if(dp[i][j] + 1 < dp[i + dl[d]][j + dc[d]] && mt[i + dl[d]][j + dc[d]] == '.') {
dp[i + dl[d]][j + dc[d]] = dp[i][j] + 1;
if(in[i + dl[d]][j + dc[d]] == false) {
coada.push({i + dl[d], j + dc[d]});
in[i + dl[d]][j + dc[d]] = true;
}
}
}
}
/*for (int i = 1; i <= n; ++i){
for (int j =1; j <= m; ++j) {
cout << dp[i][j] << " ";
}
cout << '\n';
}*/
bfs(x.first, x.second);
/*cout << '\n';
for (int i = 1; i <= n; ++i){
for (int j =1; j <= m; ++j) {
cout << dp[i][j] << " ";
}
cout << '\n';
}*/
fout << dp[y.first][y.second];
return 0;
}