struct care{
int x, y, steps;
string dir;
};
void dxt(){
int N, M;
cin >> N >> M;
vector<vector<char>> gr(N, vector<char> (M));
vector<vector<int>> dist(N, vector<int> (M, 105));
pair<int,int> st, ed;
for(int i = 0; i < N; ++i){
for(int j = 0; j < M; ++j){
cin >> gr[i][j];
if(gr[i][j] == 'S')
st = {i, j};
if(gr[i][j] == 'F')
ed = {i, j};
}
}
auto valid = [&](int x, int y){
if(x < 0 || x >= N || y < 0 || y >= M)
return false;
if(gr[x][y] == 'X')
return false;
return true;
};
const map<pair<int, int>, string> nextDir = {
{{-1, -1}, "LU"}, {{-1, 0}, "U"}, {{-1, 1}, "RU"},
{{0, -1}, "L"}, {{0, 1}, "R"},
{{1, -1}, "LD"}, {{1, 0}, "D"}, {{1, 1}, "RD"}
};
queue<care> q;
q.push({st.first, st.second, 0, "C"});
int ans = -1;
while(!q.empty()){
care curr = q.front();
q.pop();
int x = curr.x, y = curr.y, curr_step = curr.steps;
string dir = curr.dir;
debug(x, y, curr_step, dir);
if(x == ed.first && y == ed.second){
ans = curr_step;
break;
}
dist[st.first][st.second] = 0;
if(!valid(x, y))
continue;
if(dir == "C"){
for(auto var : nextDir){
int xx = var.first.first + x, yy = var.first.second + y;
string newDir = var.second;
if(valid(xx,yy)){
q.push({xx, yy, 1, newDir});
dist[xx][yy] = 1;
}
}
}
else{
for(auto var : nextDir){
int xx = var.first.first + x, yy = var.first.second + y;
string newDir = var.second;
if(valid(xx,yy) && dist[xx][yy] > curr_step + 1){
if(newDir == dir){
q.push({xx, yy, curr_step, newDir});
dist[xx][yy] = curr_step;
}
else{
q.push({xx, yy, curr_step + 1, newDir});
dist[xx][yy] = curr_step + 1;
}
}
}
}
}
cout << ans << endl;
}