#include <cstdio>
#include <queue>
#include <iostream>
using namespace std;
const int NMAX = 1000;
char v[NMAX+3][NMAX+3];
int a[NMAX][NMAX];
int r,c;
const int iplus[4] = {0,0,-1,1};
const int jplus[4] = {1,-1,0,0};
struct square
{
int x,y;
};
bool operator<(const square &c,const square &b)
{
return a[c.x][c.y] < a[b.x][b.y];
}
priority_queue <square> h;
queue <square> q;
square start,finish;
void makecost()
{
for(int i = 1;i <= r;i ++)
{
for(int j = 1;j <= c;j ++)
{
if(v[i][j] == 'D')
q.push({i,j});
if(v[i][j] == 'I')
{
start = {i,j};
v[i][j] = '.';
}
if(v[i][j] == 'O')
{
finish = {i,j};
v[i][j] = '.';
}
}
}
while(q.size() > 0)
{
square s = q.front();
q.pop();
for(int dir = 0;dir < 4;dir ++)
{
int x = s.x + iplus[dir];
int y = s.y + jplus[dir];
if(v[x][y] == '.' && a[x][y] == 0)
{
a[x][y] = a[s.x][s.y] + 1;
q.push({x,y});
}
}
}
}
bool check[NMAX][NMAX];
bool l[NMAX][NMAX];
void makeanswer()
{
int minim = 99999999;
h.push(start);
while(!h.empty())
{
square s = h.top();
h.pop();
if(check[s.x][s.y] == 1)
continue;
check[s.x][s.y] = 1;
if(a[s.x][s.y] < minim)
minim = a[s.x][s.y];
//printf("%d %d %d\n",s.x,s.y, a[s.x][s.y]);
if(s.x == finish.x && s.y == finish.y)
{
printf("%d\n",minim);
return ;
}
for(int dir = 0;dir < 4;dir ++)
{
int x = s.x + iplus[dir];
int y = s.y + jplus[dir];
if( (v[x][y] == '.' || v[x][y] == 'D' ) && check[s.x][s.y] == 1){
h.push({x,y});
}
}
}
printf("-1\n");
return;
}
int main()
{
freopen("barbar.in","r",stdin);
freopen("barbar.out","w",stdout);
scanf("%d %d\n",&r,&c);
for(int i = 1;i <= r;i ++)
{
fgets(v[i]+1,NMAX+3,stdin);
//fputs(v[i],stdout);
}
makecost();
makeanswer();
return 0;
}