#include <fstream.h>
#define min(a, b) (a < b ? a : b)
int R, C, i, j, l[2] = {-1, -1}, o = 0, v[2][2][1050000], m[1050][1050], iesirex, iesirey, m2[1050][1050];
int pozbarx, pozbary, block = 0, nr2 = 1, a, b, chestie, avx;
char cit[1500], dummy[7];
void citire ()
{
memset (m, -1, sizeof (m));
memset (m2, -1, sizeof (m2));
ifstream fin ("barbar.in");
fin >> R >> C;
fin.getline (dummy, 5);
for (i = 0; i < R; i++)
{
fin.getline (cit, 1050);
for (j = 0; j < C; j++)
{
if (cit[j] != '.')
{
if (cit[j] == 'D')
{
m[i][j] = - 3;
m2[i][j] = 0;
v[0][0][++l[0]] = i;
v[0][1][l[0]] = j;
}
else
{
if (cit[j] == '*')
{
m[i][j] = -2;
m2[i][j] = -2;
}
else
{
if (cit[j] == 'I')
{
pozbarx = i;
pozbary = j;
}
else
{
iesirex = i;
iesirey = j;
}
}
}
}
}
}
fin.close ();
}
void ChangeD (int x, int y, int avx)
{
if (x == -1 || x == R || y == -1 || y == C || m2[x][y] != -1) return;
m2[x][y] = nr2;
v[avx][0][++l[avx]] = x;
v[avx][1][l[avx]] = y;
block = 0;
}
/*void Scriere ()
{
for (i = 0; i < R; i++)
{
for (j = 0; j < C; j++)
{
cout << m[i][j] << " ";
}
cout << "\n";
}
cout << "\n\n\n";
}*/
void DStep (int &o)
{
avx = (o + 1) & 1;
l[avx] = -1;
block = 1;
for (i = 0; i <= l[o]; i++)
{
a = v[o][0][i];
b = v[o][1][i];
ChangeD (a + 1, b, avx);
ChangeD (a - 1, b, avx);
ChangeD (a, b + 1, avx);
ChangeD (a, b - 1, avx);
}
o = avx;
nr2++;
}
void diverse ()
{
l[0] = 0;
v[0][0][0] = pozbarx;
v[0][1][0] = pozbary;
m[pozbarx][pozbary] = m2[pozbarx][pozbary];
block = 0;
o = 0;
}
void ChangeBar (int x, int y, int avx, int xvechi, int yvechi)
{
if (x == -1 || x == R || y == -1 || y == C || m[x][y] == -2) return;
chestie = min (m2[x][y], m[xvechi][yvechi]);
if (m[x][y] < chestie)
{
block = 0;
m[x][y] = chestie;
v[avx][0][++l[avx]] = x;
v[avx][1][l[avx]] = y;
}
}
void BStep (int &o)
{
avx = (o + 1) & 1;
l[avx] = -1;
block = 1;
for (i = 0; i <= l[o]; i++)
{
a = v[o][0][i];
b = v[o][1][i];
ChangeBar (a - 1, b, avx, a, b);
ChangeBar (a + 1, b, avx, a, b);
ChangeBar (a, b - 1, avx, a, b);
ChangeBar (a, b + 1, avx, a, b);
}
o = avx;
}
void scriere ()
{
ofstream fout ("barbar.out");
fout << m[iesirex][iesirey];
fout.close ();
}
int main ()
{
citire ();
while (!block) DStep (o);
diverse ();
while (!block) BStep (o);
scriere ();
return 0;
}