#include <iostream>
#include <queue>
#include <string>
using namespace std;
int r, c;
char map[1001][1001];
bool hash[1001][1001];
int tu[1001][1001];
void read()
{
scanf("%d %d", &r, &c);
getchar();
for(int i = 0; i < r; i ++) gets(map[i]);
}
struct nod
{
int x, y;
};
int move[4][2]={{-1, 0}, {0, 1}, {1, 0}, {0, -1}};
queue <nod> q;
bool check(nod st)
{
if(st.x < 0 || st.y < 0 || st.x >=r || st.y >= c)
return false;
if(map[st.x][st.y] == '#' || map[st.x][st.y] == 'J') return false;
return true;
}
void bfs()
{
int i, j, step = 0, size;
nod temp, t;
while(!q.empty())
{
size = q.size();
while(size --)
{
temp = q.front();
q.pop();
for(i = 0; i < 4; i ++)
{
t.x = temp.x + move[i][0];
t.y = temp.y + move[i][1];
if(tu[t.x][t.y] > step + 1 && check(t))
{
tu[t.x][t.y] = step + 1;
q.push(t);
}
}
}
step ++;
}
}
bool final(nod sta)
{
if(sta.x < 0 || sta.y < 0 || sta.x >= r || sta.y >= c)
return true;
return false;
}
bool ok(nod sta, int step)
{
if(map[sta.x][sta.y] == '#' || tu[sta.x][sta.y] <= step + 1 || hash[sta.x][sta.y])
return false;
return true;
}
bool expend(nod sta, int step)
{
nod t;
for(int i = 0; i < 4; i ++)
{
t.x = sta.x + move[i][0];
t.y = sta.y + move[i][1];
if(final(t)) return true;
if(ok(t, step))
{
hash[t.x][t.y] = 1;
q.push(t);
}
}
return false;
}
int bfs_person(int x, int y)
{
int i, j, step = 0, size;
while(!q.empty()) q.pop();
nod temp, t;
temp.x = x;
temp.y = y;
q.push(temp);
while(!q.empty())
{
size = q.size();
while(size --)
{
temp = q.front();
q.pop();
if(expend(temp, step)) return step + 1;
}
step ++;
}
return -1;
}
void solve()
{
int i, j, x, y;
nod tp;
for(i = 0; i < r; i ++)
for(j = 0; j < c; j ++)
tu[i][j] = 999999;
while(!q.empty()) q.pop();
for(i = 0; i < r; i ++)
for(j = 0; j < c; j ++)
{
if(map[i][j] == 'F')
{
tp.x = i; tp.y = j;
tu[i][j] = 0;
q.push(tp);
}
if(map[i][j] == 'J')
{
x = i;
y = j;
}
}
bfs();
int ans = bfs_person(x, y);
if(ans < 0) puts("IMPOSSIBLE");
else printf("%d\n",ans);
}
int main()
{
read();
solve();
}