#include <bits/stdc++.h>
using namespace std;

const int INF = -987654321;
int r, c, fire[1004][1004], jh[1004][1004], yi, xi, y, x, ret;
char a[1004][1004];
int dy[] = {-1, 0, 1, 0};
int dx[] = {0, 1, 0, -1};
queue<pair<int, int>> q;

int main(){
    cin >> r >> c;
    fill(&fire[0][0], & fire[0][0] + 1004 * 1004, INF);
    for(int i = 0; i < r; i++){
        for(int j = 0; j < c; j++){
            cin >> a[i][j];
            if(a[i][j] == 'F'){
                q.push({i, j});
                fire[i][j] = 1;
            }
            else if(a[i][j] == 'J'){
                yi = i, xi = j;
            }
        }
    }
    
    while(q.size()){
        tie(y, x) = q.front();
        q.pop();
        
        for(int i = 0; i < 4; i++){
            int ny = y + dy[i];
            int nx = x + dx[i];
            if(ny < 0 || ny >= r || nx < 0 || nx >= c || fire[ny][nx] != INF || a[ny][nx] == '#') continue;
            q.push({ny, nx});
            fire[ny][nx] = fire[y][x] + 1;
        }
    }
    
    q.push({yi, xi});
    jh[yi][xi] = 1;
    while(q.size()){
        tie(y, x) = q.front();
        q.pop();
        
        if(y == 0 || y == r - 1 || x == 0 || x == c - 1){
            ret = jh[y][x];
            break;
        }
        
        for(int i = 0; i < 4; i++){
            int ny = y + dy[i];
            int nx = x + dx[i];
            if(ny < 0 || ny >= r || nx < 0 || nx >= c || jh[ny][nx] || a[ny][nx] == '#') continue;
            if(fire[ny][nx] <= jh[y][x] + 1) continue;
            q.push({ny, nx});
            jh[ny][nx] = jh[y][x] + 1;
        }
    }
    if(ret != 0) cout << ret << '\n';
    else cout << "IMPOSSIBLE\n";
}