#include <fstream>
#include <queue>
#define sizes [1001][1001]
using namespace std;
char c sizes;
int rasp sizes, dragon sizes, iorg, jorg, ies, jes, n, m, sol = 0, maxi = 0;
queue<pair<int,int>> bfs;
bool isvaliddragon(int i, int j)
{
if(i >= 0 && j >= 0 && j < m && i < n && dragon[i][j] == -1)
return true;
return false;
}
bool isvalid(int i, int j, int dep)
{
if(i >= 0 && j >= 0 && j < m && i < n && rasp[i][j] == -1 && dragon[i][j] >= dep)
return true;
return false;
}
int dx[]={1, -1, 0, 0};
int dy[]={0, 0, 1, -1};
int main()
{
ifstream fin("barbar.in");
ofstream fout("barbar.out");
fin >> n >> m;
for (int i = 0; i < n; i++)
{
fin >> c[i];
for (int j = 0; j < m; j++)
{
if (c[i][j] == 'I')
{
iorg = i;
jorg = j;
}
if (c[i][j] == 'D')
{
bfs.push({i, j});
dragon[i][j] = 0;
}
else
dragon[i][j] = -1;
if (c[i][j] == '*')
{
rasp[i][j] = -2;
dragon[i][j] = -2;
}
if (c[i][j] == 'O')
{
ies = i;
jes = j;
}
}
}
while (bfs.size())
{
int i = bfs.front().first, j = bfs.front().second;
for (int k = 0; k <= 3; k++)
{
if (isvaliddragon(i+dx[k], j+dy[k]))
{
bfs.push({i+dx[k], j+dy[k]});
dragon[i+dx[k]][j+dy[k]] = dragon[i][j] + 1;
maxi = max(maxi, dragon[i+dx[k]][j+dy[k]]);
}
}
bfs.pop();
}
int dr = maxi+1, st = 0, mij;
while (dr - st > 1)
{
mij = (dr+st)/2;
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
if (rasp[i][j] != -2)
rasp[i][j] = -1;
bfs.push({iorg, jorg});
rasp[iorg][jorg] = 0;
while (bfs.size())
{
int i = bfs.front().first, j = bfs.front().second;
for (int k = 0; k <= 3; k++)
{
if (isvalid(i+dx[k], j+dy[k], mij))
{
bfs.push({i+dx[k], j+dy[k]});
rasp[i+dx[k]][j+dy[k]] = rasp[i][j] + 1;
}
}
bfs.pop();
}
if (rasp[ies][jes] != -1)
{
sol = max(sol, mij);
st = mij;
}
else
dr = mij;
}
if (dragon[iorg][jorg] < sol)
sol = dragon[iorg][jorg];
if (sol != 0)
fout << sol;
else fout << -1;
return 0;
}