Pagini recente » Cod sursa (job #2721645) | Cod sursa (job #2205966) | Cod sursa (job #1694899) | Cod sursa (job #1644356) | Cod sursa (job #2079801)
#include<cstdio>
#include<utility>
#include<deque>
#define f first
#define s second
using namespace std;
const int dx[4]={-1, 0, 1, 0};
const int dy[4]={0, 1, 0, -1};
pair<int,int> pozInit, pozFin;
int n, m, a[1005][1005], lastViz[1005][1005];
inline void citire(){
deque<pair<int,int> > cd;
char s[1005];
int i, j, k, x, y;
scanf("%d%d\n", &n, &m);
for (i=1;i<=n;i++) {a[i][0]=-1; a[i][m+1]=-1;}
for (i=1;i<=m;i++) {a[0][i]=-1; a[n+1][i]=-1;}
for (i=1;i<=n;i++) {
gets(s);
for (j=0;j<m;j++) {
lastViz[i][j+1]=0;
switch (s[j]) {
case '.': {a[i][j+1]=n*m+1; break;}
case '*': {a[i][j+1]=-1; break;}
case 'D': {a[i][j+1]=0; cd.push_back(make_pair(i, j+1)); break;}
case 'I': {a[i][j+1]=n*m+1; pozInit=make_pair(i, j+1); break;}
case 'O': {a[i][j+1]=n*m+1; pozFin=make_pair(i, j+1); break;}
}
}
}
while (!cd.empty()) {
x=(cd.front()).f; y=(cd.front()).s; cd.pop_front();
for (k=0;k<=3;k++) if (a[x+dx[k]][y+dy[k]]>a[x][y]+1) {
a[x+dx[k]][y+dy[k]]=a[x][y]+1;
cd.push_back(make_pair(x+dx[k], y+dy[k]));
}
}
}
bool correct(int lenMin){
int x, y, k;
deque<pair<int,int> > cda;
cda.push_back(pozInit);
while (!cda.empty()) {
x=(cda.front()).f; y=(cda.front()).s; cda.pop_front();
for (k=0;k<=3;k++) if ((a[x+dx[k]][y+dy[k]]>=lenMin)&&(lastViz[x+dx[k]][y+dy[k]]!=lenMin)) {
if ((x+dx[k]==pozFin.f)&&(y+dy[k]==pozFin.s)) return true;
cda.push_back(make_pair(x+dx[k], y+dy[k]));
lastViz[x+dx[k]][y+dy[k]]=lenMin;
}
}
return false;
}
int main(){
freopen("barbar.in","r",stdin);
freopen("barbar.out","w",stdout);
citire();
int st=1, dr=a[pozInit.first][pozInit.second], mij, sol=-1;
while (st<=dr) {
mij=st+(dr-st)/2;
if (correct(mij)) {sol=mij; st=mij+1;} else dr=mij-1;
}
printf("%d\n", sol);
return 0;
}