Pagini recente » Cod sursa (job #2146010) | Cod sursa (job #988848) | Cod sursa (job #715572) | Cod sursa (job #1809883) | Cod sursa (job #2989019)
#include <bits/stdc++.h>
using namespace std;
const int N = 1002;
const int dl[] = {-1, 0, 1, 0};
const int dc[] = {0, -1, 0, 1};
char a[N][N];
int b[N][N];
int f[N][N];
struct c{ // coordonate
int l, c;
};
int main()
{
ifstream in("barbar.in");
ofstream out("barbar.out");
queue <c> q;
queue <c> p;
int n , m;
in >> n >> m;
int lf, cf;
for(int i = 1; i <= n; i++){
for(int j = 1; j <= m; j++){
in >> a[i][j];
switch(a[i][j]){
case '.':
b[i][j] = -1;
break;
case '*':
b[i][j] = -2;
break;
case 'D':
b[i][j] = 0;
q.push((c){i,j});
break;
case 'I':
b[i][j] = -1;
p.push((c){i,j});
break;
case 'O':
b[i][j] = -1;
lf = i;
cf = j;
break;
}
}
}
while(!q.empty()){
c x = q.front();
q.pop();
for(int k = 0; k < 4; k++){
c y;
y.l = x.l + dl[k];
y.c = x.c + dc[k];
if(b[y.l][y.c] == -1){
b[y.l][y.c] = b[x.l][x.c] + 1;
q.push((c){y.l,y.c});
}
}
}
f[p.front().l][p.front().c] = b[p.front().l][p.front().c];
while(!p.empty()){
c x = p.front();
//f[x.l][x.c] = min(f[x.l][x.c], b[x.l][x.c]);
p.pop();
for(int k = 0; k < 4; k++){
c y;
y.l = x.l + dl[k];
y.c = x.c + dc[k];
if(b[y.l][y.c] > 0 && f[y.l][y.c] < f[x.l][x.c]){ //daca pot parcurge celula
// nu ma intereseaza daca a mai fost parcursa ci daca este distanta minima este mai mare
f[y.l][y.c] = min(f[x.l][x.c], b[y.l][y.c]);
p.push((c){y.l,y.c});
}
}
}
/*
for(int i = 1; i <= n; i++){
for(int j = 1; j <= m; j++){
out << f[i][j] << " ";
}
out << '\n';
}*/
if(f[lf][cf] == 0){
out << -1;
}
else
out << f[lf][cf];
return 0;
}