#include <bits/stdc++.h>
using namespace std;
const int N = 2e6 + 5;
char ch;
int ans_a, ans_b, idx, n, m;
int vis[N], b[N], a[N], dfn[N], inque[N];
vector<int> c[N];
void fill_(int p) {
  if (vis[p]) return;
  vis[p] = 1;
  fill_(b[p]);
  for (int v : c[p]) fill_(v);
}
void bfs(int p, int mx) {
  queue<pair<int, int> > que;
  que.push(pair<int, int>(0, p));
  inque[p] = 1;
  vector<int> ans(mx);
  while (!que.empty()) {
    pair<int, int> t = que.front();
    que.pop();
    int u = t.second, cnt = t.first;
    if (!a[u]) ans[cnt % mx] = 1;
    for (int v : c[u]) {
      if (!inque[v]) que.push(pair<int, int>(cnt + 1, v));
      inque[v] = 1;
    }
  }
  ans_a += mx;
  for (int i = 0; i < mx; i++)
    if (ans[i]) ans_b++;
}
void dfs(int p) {
  if (dfn[p]) {
    bfs(p, idx + 1 - dfn[p]);
    return;
  }
  dfn[p] = ++idx, dfs(b[p]);
}
void solve() {
  cin >> n >> m;
  idx = ans_a = ans_b = 0;
  for (int i = 0; i < n * m; i++) vis[i] = dfn[i] = inque[i] = 0, c[i].clear();
  for (int i = 0; i < n; i++)
    for (int j = 0; j < m; j++) {
      int p = i * m + j;
      cin >> ch;
      a[p] = ch - '0';
    }
  for (int i = 0; i < n; i++)
    for (int j = 0; j < m; j++) {
      int p = i * m + j;
      cin >> ch;
      switch (ch) {
        case 'L':
          b[p] = p - 1;
          c[p - 1].push_back(p);
          break;
        case 'R':
          b[p] = p + 1;
          c[p + 1].push_back(p);
          break;
        case 'U':
          b[p] = p - m;
          c[p - m].push_back(p);
          break;
        case 'D':
          b[p] = p + m;
          c[p + m].push_back(p);
      }
    }
  for (int i = 0; i < n; i++)
    for (int j = 0; j < m; j++) {
      int p = i * m + j;
      if (!vis[p]) dfs(p);
      fill_(p);
    }
  cout << ans_a << ' ' << ans_b << '\n';
}
int main() {
  ios::sync_with_stdio(false);
  int T;
  cin >> T;
  while (T--) solve();
}
