#define pr(x) cout << x << endl
#define yesno(x) cout << ((x) ? "YES\n" : "NO\n")
const int N = 100100;
void solve(){
ios_base::sync_with_stdio(false); cin.tie(NULL);
int n,m;
cin >> m >> n;
vector<vector<char>> gr(n, vector<char>(m));
pair<int,int> st, end;
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')
end = {i,j};
}
}
int dist[n][m][8];
memset(dist, -1, sizeof(dist));
// LU U RU
// L * R
// LD D RD
queue<pair<pair<int,int>,int>> q;
int dx[8] = {-1, -1, -1, 0, 0, 1, 1, 1};
int dy[8] = {-1, 0, 1, -1, 1, -1, 0, 1};
for(int i = 0; i < 8; ++i){
q.push({st,i});
dist[st.first][st.second][i] = 1;
}
while(!q.empty()){
auto [x,y] = q.front().first;
auto d = q.front().second;
q.pop();
for(int k = 0; k < 8; ++k){
int xx = x + dx[k], yy = y + dy[k];
if(xx < 0 || xx >= n || yy < 0 || yy >= m || gr[xx][yy] == 'X')
continue;
int cost = (d == k) ? 0 : 1;
if(dist[xx][yy][k] == -1 || dist[xx][yy][k] > dist[x][y][d] + cost){
dist[xx][yy][k] = dist[x][y][d] + cost;
q.push({{xx,yy},k});
}
}
}
int ans = 101;
for(int i = 0; i < 8; i++){
if(dist[end.first][end.second][i] == -1)
continue;
ans = min(ans, dist[end.first][end.second][i]);
}
ans = (ans == 101) ? -1 : ans;
pr(ans);
}
signed main(){
ios_base::sync_with_stdio(false); cin.tie(NULL);
int t; cin >> t;
while(t--){
solve();
}
}