#include <iostream>
#include <iomanip>
#include <sstream>
#include <cstdio>
#include <string>
#include <vector>
#include <algorithm>
#include <complex>
#include <cstring>
#include <cstdlib>
#include <cmath>
#include <cassert>
#include <climits>
#include <queue>
#include <set>
#include <map>
#include <valarray>
#include <bitset>
#include <stack>
using namespace std;

#define REP(i,n) for(int i=0;i<(int)n;++i)
#define FOR(i,c) for(__typeof((c).begin())i=(c).begin();i!=(c).end();++i)
#define ALL(c) (c).begin(), (c).end()
typedef long long ll;
typedef pair<int,int> pii;
const int INF = 1<<29;
const double PI = acos(-1);
const double EPS = 1e-8;

struct Edge {
  int dst;
  char c;
};

typedef vector<vector<Edge> > G;
const int N = 100005;
bool visited[N];

void bfs(const G &g, int s, vector<int> &v) {
  int n = g.size();
  REP(i,n) visited[i] = 0;
  queue<int> Q; Q.push(s);
  visited[s] = 1;
  while(!Q.empty()) {
    int now = Q.front(); Q.pop();
    v.push_back(now);
    FOR(it, g[now]) {
      if (it->c == 'N') continue;
      int dst = it->dst;
      if (!visited[dst]) {
        visited[dst] = 1;
        Q.push(dst);
      }
    }
  }
}

void bfs2(const G &g, const vector<int> &v, int *dist) {
  int n = g.size();
  REP(i,n) dist[i] = INF;
  queue<int> Q;
  FOR(it, v) {
    Q.push(*it);
    dist[*it] = 0;
  }
  while(!Q.empty()) {
    int now = Q.front(); Q.pop();
    FOR(it, g[now]) {
      if (it->c == 'L') continue;
      int dst = it->dst;
      if (dist[dst] == INF) {
        dist[dst] = dist[now] + 1;
        Q.push(dst);
      }
    }
  }
}

int dist1[N];
int dist2[N];
int dist3[N];

int main() {
  int T;
  cin >> T;
  while(T--) {
    int n, m;
    cin >> n >> m;
    int ns, ls;
    cin >> ns >> ls;
    G g(n+1);
    REP(i,m) {
      char c;
      int a,b;
      cin >> a >> b >> c;
      g[a].push_back((Edge){b,c});
      g[b].push_back((Edge){a,c});
    }
    vector<int> vA;             // レノンがいる場所から自由にいける場所
    vector<int> vB;             // 夏への扉から自由にいける場所
    bfs(g,ls,vA);
    bfs(g,0,vB);
    if (find(ALL(vA),0) != vA.end()) {
      cout << 0 << endl;
      continue;
    }
    bfs2(g,vA,dist1);
    bfs2(g,vB,dist2);
    bfs2(g,vector<int>(1,ns),dist3);
    int ans = INF;
    REP(i,n+1) {
      //cout << dist1[i] << " " << dist2[i] << " " << dist3[i] << endl;
      ans = min(ans, dist1[i]+dist2[i]+dist3[i]);
    }
    cout << ans << endl;
  }
}