#include <bits/stdc++.h>
//std::ifstream fin ("input.txt");
//std::ofstream fout ("output.txt");
std::ifstream fin ("barbar.in");
std::ofstream fout ("barbar.out");
int dp[1005][1005];
int dragon[1005][1005];
bool a[1005][1005];
struct str{
int cost, i, j;
str(int cost, int i, int j)
: cost(cost), i(i), j(j)
{
}
};
struct compare {
bool operator() (str const& p1, str const& p2){
return p1.cost > p2.cost;
}
};
std::deque < std::pair < int, int > > dq;
std::priority_queue < str, std::vector < str >, compare > pq;
void BFS_dragons (int n, int m){
int di[4] = {-1, 0, 1, 0};
int dj[4] = {0, -1, 0, 1};
int ii, jj, i, j;
while (!dq.empty()){
i = dq.front().first;
j = dq.front().second;
dq.pop_front();
for (int k=0; k<4; k++){
ii = i + di[k];
jj = j + dj[k];
if (0 <= ii and ii < n)
if (0 <= jj and jj < m)
if (a[ii][jj] == 0)
if (dragon[ii][jj] > dragon[i][j] + 1){
dragon[ii][jj] = dragon[i][j] + 1;
dq.push_back ({ii, jj});
}
}
}
}
void BFS_player (int n, int m){
int di[4] = {-1, 0, 1, 0};
int dj[4] = {0, -1, 0, 1};
int i, j, ii, jj;
while (!pq.empty()){
i = pq.top().i;
j = pq.top().j;
pq.pop();
for (int k=0; k<4; k++){
ii = i + di[k];
jj = j + dj[k];
if (0 <= ii and ii < n)
if (0 <= jj and jj < m)
if (a[ii][jj] == 0)
if (dp[ii][jj] < std::min (dp[i][j], dragon[ii][jj])){
dp[ii][jj] = std::min (dp[i][j], dragon[ii][jj]);
pq.push ({dp[ii][jj], ii, jj});
}
}
}
}
int main()
{
int n, m, i, j;
int sx, sy, fx, fy;
char chr;
fin >> n >> m;
std::string s;
for (i=0; i<n; i++){
fin >> s;
for (j=0; j<m; j++){
dragon[i][j] = INT_MAX;
dp[i][j] = -1;
chr = s[j];
if (chr == '.'){
a[i][j] = 0;
continue;
}
if (chr == '*'){
a[i][j] = 1;
continue;
}
if (chr == 'I'){
a[i][j] = 0;
sx = i;
sy = j;
continue;
}
if (chr == 'O'){
a[i][j] = 0;
fx = i;
fy = j;
continue;
}
if (chr == 'D'){
dq.push_back ({i, j});
a[i][j] = 0;
dragon[i][j] = 0;
continue;
}
}
}
BFS_dragons (n, m);
/*
for (i=0; i<n; i++, fout << '\n')
for (j=0; j<m; j++)
fout << dragon[i][j] << ' ';
*/
dp[sx][sy] = dragon[sx][sy];
pq.push ({dp[sx][sy], sx, sy});
BFS_player (n, m);
/*
for (i=0; i<n; i++, fout << '\n')
for (j=0; j<m; j++)
fout << dp[i][j] << ' ';
*/
fout << dp[fx][fy] << '\n';
return 0;
}