https://ac.nowcoder.com/acm/contest/77231/E
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<ll, ll> PII;
typedef vector<long long> VI;
#define rep(i,a,n) for (int i=a;i<=n;i++)
#define per(i,a,n) for (int i=a;i>=n;i--)
#define pb(i) push_back(i)
#define int long long
#define INF 0x3f3f3f3f
#define oz 998244353
#define endl '\n'
#define N 200010
const int mod = 1e9 + 7;
string s[1010];
int dis[1010][1010][4];
int op[4][2] = {1, 0, -1, 0, 0, -1, 0, 1}; // 下 上 左 右
int n, m;
void solve() {
cin >> n >> m;
int u, v;
queue<vector<int>> q;
rep(i, 0, n - 1)cin >> s[i];
rep(i, 0, n - 1) {
rep(j, 0, m - 1) {
rep(k, 0, 3)
dis[i][j][k] = 1e9;
}
}
rep(i, 0, n - 1) {
rep(j, 0, m - 1) {
if (s[i][j] == 'S') {
rep(k, 0, 3) {
dis[i][j][k] = 0;
q.push({i, j, k});
}
}
if (s[i][j] == 'T') {
u = i;
v = j;
}
}
}
while (!q.empty()) {
auto t = q.front();
q.pop();
int x = t[0], y = t[1];
if (s[x][y] == 'S' || s[x][y] == 'T' || s[x][y] == '.') {
int xx = x + op[t[2]][0], yy = y + op[t[2]][1];
if (xx < n && xx >= 0 && yy >= 0 && yy < m && s[xx][yy] != '#') {
if (dis[xx][yy][t[2]] > dis[x][y][t[2]] + 1) {
q.push({xx, yy, t[2]});
dis[xx][yy][t[2]] = dis[x][y][t[2]] + 1;
}
}
}
else if (s[x][y] == '*') {
rep(i, 0, 3) {
if ((i ^ t[2]) == 1)continue;
int xx = x + op[i][0], yy = y + op[i][1];
if (xx < n && xx >= 0 && yy >= 0 && yy < m && s[xx][yy] != '#') {
if (dis[xx][yy][i] > dis[x][y][t[2]] + 1) {
q.push({xx, yy, i});
dis[xx][yy][i] = dis[x][y][t[2]] + 1;
}
}
}
}
}
// for (int i = 0; i < n; i++) {
// for (int j = 0; j < m; j++) {
// int mi = 1e9;
// for (int k = 0; k < 4; k++)mi = min(mi, dis[i][j][k]);
// cout << mi << " ";
// }
// cout << '\n';
// }
int mi = 1e9;
rep(i, 0, 3)mi = min(mi, dis[u][v][i]);
if (mi > 8e8)cout << - 1 << endl;
else cout << mi << endl;
}
signed main() {
ios::sync_with_stdio(false);
cin.tie(0), cout.tie(0);
int T = 1;
cin >> T;
while (T --)
solve();
return 0;
}