#include <iostream>
#include <string>
#include <cmath>
#include <algorithm>
#include <vector>
using namespace std;
long long get_knight_dist(long long dx, long long dy) {
if (dx < dy) swap(dx, dy);
if (dx == 1 && dy == 0) return 3;
if (dx == 2 && dy == 2) return 4;
long long steps = max((dx + 1) / 2, (dx + dy + 2) / 3);
steps += (steps ^ dx ^ dy) & 1;
return steps;
}
void solve() {
string p;
long long a, b, c, d;
cin >> p >> a >> b >> c >> d;
long long dx = abs(a - c);
long long dy = abs(b - d);
bool Q = p.find('Q') != string::npos;
bool R = p.find('R') != string::npos;
bool B = p.find('B') != string::npos;
bool N = p.find('N') != string::npos;
bool K = p.find('K') != string::npos;
bool P = p.find('P') != string::npos;
if (a == c && b == d) {
cout << 0 << "\n";
return;
}
if (Q && (dx == 0 || dy == 0 || dx == dy)) { cout << 1 << "\n"; return; }
if (R && (dx == 0 || dy == 0)) { cout << 1 << "\n"; return; }
if (B && (dx == dy)) { cout << 1 << "\n"; return; }
if (N && ((dx == 1 && dy == 2) || (dx == 2 && dy == 1))) { cout << 1 << "\n"; return; }
if (K && (max(dx, dy) == 1)) { cout << 1 << "\n"; return; }
if (P && (c - a == 1 && dy == 0)) { cout << 1 << "\n"; return; }
if (Q || R) {
cout << 2 << "\n";
return;
}
long long ans = 2e18;
if (B) {
if ((dx + dy) % 2 == 0) {
ans = min(ans, 2LL);
} else if (P || K || N) {
ans = min(ans, 3LL);
}
}
if (N) ans = min(ans, get_knight_dist(dx, dy));
if (K) ans = min(ans, max(dx, dy));
if (P && dy == 0 && c > a) ans = min(ans, c - a);
if (ans >= 2e18) {
cout << -1 << "\n";
} else {
cout << ans << "\n";
}
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int q;
if (cin >> q) {
while (q--) solve();
}
return 0;
}