Pagini recente » Cod sursa (job #486230) | Cod sursa (job #58024) | Cod sursa (job #979436) | Cod sursa (job #333719) | Cod sursa (job #2319028)
#include <fstream>
#include <cstring>
#include <queue>
#define DIM 1010
#define inf 2000000000
using namespace std;
ifstream fin ("barbar.in");
ofstream fout ("barbar.out");
int d[DIM][DIM], a[DIM][DIM];
int r,c,i,j,istart,jstart,istop,jstop,iv,jv;
int di[4] = {0, 0, 1, -1};
int dj[4] = {1, -1, 0 ,0};
char ch[DIM][DIM];
queue < pair <int, int> > q;
int main() {
fin>>r>>c;
for (i=1; i<=r; i++){
for (j=1; j<=c; j++){
fin>>ch[i][j];
if (ch[i][j]=='D'){
q.push(make_pair(i, j));
a[i][j]=0;
}
else {
if (ch[i][j]=='I'){
istart=i;
jstart=j;
}
else if (ch[i][j]=='O'){
istop=i;
jstop=j;
}
a[i][j]=inf;
}
}
}
while (!q.empty()){
i=q.front().first;
j=q.front().second;
q.pop();
for (int dir=0; dir<4; dir++){
iv=i+di[dir];
jv=j+dj[dir];
if (i >= 1 && i <= r && j >= 1 && j <= c && ch[i][j] != '*'&& a[iv][jv] > a[i][j] + 1){
a[iv][jv]=a[i][j]+1;
q.push(make_pair(iv, jv));
}
}
}
memset(d,0,sizeof(d));
q.push(make_pair(istart, jstart));
d[istart][jstart]=a[istart][jstart];
while (!q.empty()){
i=q.front().first;
j=q.front().second;
q.pop();
for (int dir=0; dir<4; dir++) {
iv=i+di[dir];
jv=j+dj[dir];
if (i >= 1 && i <= r && j >= 1 && j <= c && ch[i][j] != '*'){
if (d[iv][jv]==-1){
d[iv][jv]=min(a[iv][jv], d[i][j]);
q.push(make_pair(iv, jv));
}
else if (d[iv][jv] < min(d[i][j], a[iv][jv])){
d[iv][jv]=min(d[i][j], a[iv][jv]);
q.push(make_pair(iv, jv));
}
}
}
}
fout<<d[istop][jstop];
return 0;
}