#include <iostream>
#include <fstream>
#include <queue>
#define fi first
#define se second
#define nmx 1005
using namespace std;
ifstream fin ("barbar.in");
ofstream fout ("barbar.out");
int n, i, j, nr, r, c, ix, iy, ox, oy, x, y, vx, vy, rez;
int v[nmx][nmx], dl[] = {-1, 0, 1, 0}, cl[] = {0, 1, 0, -1};
string s;
deque < pair< int, int>> dq;
struct Per {
int x, y;
bool operator < (const Per &alt) const
{ return v[x][y] > v[alt.x][alt.y]; }
};
priority_queue < Per > pq;
int main () {
fin >> r >> c;
getline (fin, s);
for (i = 1; i <= r; i++) {
getline (fin, s);
for (j = 0; j < c; j++) {
if (s[j] == '.') continue;
if (s[j] == '*') v[i][j + 1] = -1;
else if (s[j] == 'D') {
v[i][j + 1] = 1;
dq.push_back ({i, j+1});
}
else if (s[j] == 'I') {
ix = i;
iy = j + 1;
}
else if (s[j] == 'O') {
ox = i;
oy = j + 1;
}
}
}
while (!dq.empty()) {
x = dq.front().fi;
y = dq.front().se;
dq.pop_front();
for (j = 0; j < 4; j++) {
vx = x + dl[j];
vy = y + cl[j];
if (v[vx][vy] == 0 && vx > 0 && vy > 0 && vx <= r && vy <= c) {
v[vx][vy] = v[x][y] + 1;
dq.push_back ({vx, vy});
}
}
}
bool ok = 0;
rez = v[ix][iy];
v[ix][iy] *= -1;
pq.push ({ix, iy});
while (!pq.empty()) {
x = pq.top().x;
y = pq.top().y;
pq.pop();
if (x == ox && y == oy) {
ok = 1;
break;
}
rez = min(rez, -v[x][y]);
for (j = 0; j < 4; j++) {
vx = x + dl[j];
vy = y + cl[j];
if (v[vx][vy] > 1 && vx > 0 && vy > 0 && vx <= r && vy <= c) {
v[vx][vy] *= -1;
pq.push ({vx, vy});
}
}
}
if (ok == 0) {
fout << -1 << "\n";
} else {
fout << rez-1 << "\n";
}
}