#include <fstream>
#define valid(x1,y1) x1&&y1>-1&&x1<=n&&y1<m
using namespace std;
int const dirx[]={0,1,0,-1}, diry[]={1,0,-1,0},dim=1001;
char mat[dim][dim];
int v[dim][dim], st, dr, n, m;
bool b[dim][dim],viz[dim][dim];
struct bar{
int a, b;
}q[dim*dim];
bool pot(int dist,bar i,bar o){
st=dr=1;
q[1]={i.a,i.b};
if(v[i.a][i.b]<dist)
return 0;
while(st<=dr){
int x=q[st].a;
int y=q[st].b;
for(int i=0;i<4;i++){
int x1=x+dirx[i];
int y1=y+diry[i];
if(x1==o.a&&y1==o.b){
if(v[x1][y1]<dist)
return 0;
return 1;
}
if(b[x1][y1]==0&&v[x1][y1]>=dist&&viz[x1][y1]==0&&valid(x1,y1)){
q[++dr]={x1,y1};
viz[x1][y1]=1;
}
}
st++;
}
return 0;
}
int main()
{
freopen ("barbar.in","r",stdin);
freopen ("barbar.out","w",stdout);
int i,j,mx=0;
bar in,o;
scanf("%d%d",&n,&m);
for(i=1;i<=n;i++)
scanf("%s",&mat[i]);
for(i=1;i<=n;i++)
for(j=0;j<m;j++){
if(mat[i][j]=='I')
in={i,j};
if(mat[i][j]=='O')
o={i,j};
if(mat[i][j]=='D')
q[++dr]={i,j};
if(mat[i][j]=='*')
b[i][j]=1;
}
st=1;
while(st<=dr){
int x=q[st].a;
int y=q[st].b;
for(i=0;i<4;i++){
int x1=x+dirx[i];
int y1=y+diry[i];
if(b[x1][y1]==0&&v[x1][y1]==0&&valid(x1,y1)){
v[x1][y1]=1+v[x][y];
mx=max(mx,v[x1][y1]);
q[++dr]={x1,y1};
}
}
st++;
}
int s=1,d=mx,r=-1;
while(s<=d){
int mij=(s+d)/2;
if(pot(mij,in,o)==1)
s=mij+1,r=mij;
else
d=mij-1;
}
printf("%d",r);
return 0;
}