#include <bits/stdc++.h>
using namespace std;
const int N = 1002;
const int dl[] = {-1, 0, 1, 0};
const int dc[] = {0, -1, 0, 1};
int b[N][N];
int f[N][N];
struct c{ // coordonate
int l, c;
};
void fiil(int n){
}
int main()
{
ifstream in("barbar.in");
ofstream out("barbar.out");
queue <c> q;
queue <c> p;
int n , m;
in >> n >> m;
int lf, cf;
char x;
for(int i = 1; i <= n; i++){
for(int j = 1; j <= m; j++){
in >> x;
switch(x){
case '.':
b[i][j] = -1;
break;
case '*':
b[i][j] = -2;
break;
case 'D':
b[i][j] = 0;
q.push((c){i,j});
break;
case 'I':
b[i][j] = -1;
p.push((c){i,j});
break;
case 'O':
b[i][j] = -1;
lf = i;
cf = j;
break;
}
}
}
int st = 0, dr = n + m - 1;
int rez = -1;
while(st <= dr){
int m = (st + dr) / 2;
if(fiil(m)){
rez = m;
st = m + 1;
}
else
dr = m - 1;
}
out << rez;
return 0;
}