#include <iostream>
#include <string>
#include <cmath>
#include <algorithm>
#include <vector>
using namespace std;
long long get_pure_N_dist(long long dx, long long dy) {
dx = abs(dx); dy = abs(dy);
if (dx == 0 && dy == 0) return 0;
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 x = c - a;
long long y = d - b;
long long dx = abs(x);
long long dy = abs(y);
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 (dx == 0 && dy == 0) {
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 && x == 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);
}
vector<pair<long long, long long>> moves;
if (P) moves.push_back({1, 0});
if (K) {
for (int i = -1; i <= 1; ++i) {
for (int j = -1; j <= 1; ++j) {
if (i != 0 || j != 0) moves.push_back({i, j});
}
}
}
if (N) {
int dxs[] = {-2, -1, 1, 2, 2, 1, -1, -2};
int dys[] = {1, 2, 2, 1, -1, -2, -2, -1};
for (int i = 0; i < 8; ++i) moves.push_back({dxs[i], dys[i]});
}
for (auto m : moves) {
long long nx = x - m.first;
long long ny = y - m.second;
if (abs(nx) == abs(ny)) {
ans = min(ans, 2LL);
}
}
if (P || K || N) ans = min(ans, 3LL);
}
if (N) {
int max_k = K ? 4 : 0;
int max_p = (!K && P) ? 4 : 0;
for (int k_x = -max_k; k_x <= max_k; ++k_x) {
for (int k_y = -max_k; k_y <= max_k; ++k_y) {
int k_moves = max(abs(k_x), abs(k_y));
if (k_moves > max_k) continue;
for (int p_moves = 0; p_moves <= max_p; ++p_moves) {
long long rem_x = x - k_x - p_moves;
long long rem_y = y - k_y;
long long n_moves = get_pure_N_dist(rem_x, rem_y);
ans = min(ans, k_moves + p_moves + n_moves);
}
}
}
}
if (!N) {
if (K) {
ans = min(ans, max(dx, dy));
} else if (P) {
if (dy == 0 && x > 0) ans = min(ans, x);
}
}
if (ans > 1e18) {
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;
}