#include <cstdio>
#include <cctype>
#include <string>
//#include <vector>
//#include <queue>
//using namespace std;
#define MAXN 1000
static int R[MAXN+1][MAXN+1], D[MAXN+1][MAXN+1], use[MAXN+1][MAXN+1], C[MAXN+1][MAXN+1];
typedef struct point {
int x, y;
} point;
/*template <class T> struct cmp : binary_function<T,T,bool> {
bool operator()(const T &a, const T &b) const {
return D[a.x][a.y]<D[b.x][b.y];
}
};*/
int main(){
freopen("barbar.in", "r", stdin);
freopen("barbar.out", "w", stdout);
int N, M, i, j, k, sx, sy, ex, ey, l[2], cq, nq, x, y;
int dx[4]={-1, 0, 1, 0}, dy[4]={0, 1, 0, -1};
char c;
static point Q[2][MAXN*MAXN+10];
//priority_queue< point, vector<point>, cmp<point> > A;
memset(D, 0, sizeof(D));
memset(use, 0, sizeof(use));
l[0]=0;
scanf("%d%d", &N, &M);
for(i=0; i<N; i++)
for(j=0; j<M; j++){
scanf("%c", &c);
while(isspace(c))
scanf("%c", &c);
if(c=='.')
R[i][j]=0;
else if(c=='*')
R[i][j]=1;
else if(c=='I'){
R[i][j]=0;
sx=i; sy=j;
}
else if(c=='O'){
R[i][j]=0;
ex=i; ey=j;
}
else if(c=='D'){
R[i][j]=0;
Q[0][l[0]].x=i;
Q[0][l[0]].y=j;
use[i][j]=1;
l[0]++;
}
}
cq=0; l[1]=0;
while(l[cq]){
nq=1-cq;
/*for(i=0; i<N; i++){
for(j=0; j<M; j++)
printf("%d ", D[i][j]);
printf("\n");
}*/
for(k=0; k<l[cq]; k++){
for(i=0; i<4; i++){
x=Q[cq][k].x+dx[i];
y=Q[cq][k].y+dy[i];
if(0<=x && x<N && 0<=y && y<M && !R[x][y] && !use[x][y]){
D[x][y]=D[Q[cq][k].x][Q[cq][k].y]+1;
use[x][y]=1;
Q[nq][l[nq]].x=x;
Q[nq][l[nq]].y=y;
l[nq]++;
}
}
}
l[cq]=0;
cq=nq;
}
/*for(i=0; i<N; i++){
for(j=0; j<M; j++)
printf("%d ", D[i][j]);
printf("\n");
}
printf("\n");*/
for(i=0; i<N; i++)
for(j=0; j<M; j++)
C[i][j]=-1;
Q[0][0].x=sx;
Q[0][0].y=sy;
l[0]=1;
C[sx][sy]=D[sx][sy];
cq=0; l[1]=0;
while(l[cq]){
nq=1-cq;
/*for(i=0; i<N; i++){
for(j=0; j<M; j++)
printf("%2d ", C[i][j]);
printf("\n");
}*/
for(k=0; k<l[cq]; k++){
for(i=0; i<4; i++){
x=Q[cq][k].x+dx[i];
y=Q[cq][k].y+dy[i];
if(0<=x && x<N && 0<=y && y<M && !R[x][y]){
if(C[x][y]<D[x][y] && C[Q[cq][k].x][Q[cq][k].y]>C[x][y]){
C[x][y]=(C[Q[cq][k].x][Q[cq][k].y]<D[x][y])? C[Q[cq][k].x][Q[cq][k].y]: D[x][y];
Q[nq][l[nq]].x=x;
Q[nq][l[nq]].y=y;
l[nq]++;
}
}
}
}
l[cq]=0;
cq=nq;
}
printf("%d\n", C[ex][ey]);
return 0;
}