#include <bits/stdc++.h>
using namespace std;
int T, n, m, p, k, a[20];
long long _k[20], pre[20], tmp[20];
char c[20][20];
long long calc(int p) {
  tmp[p] = a[p];
  for (int i = p + 1; i <= n; i++) tmp[i] = _k[i - p] * a[i] + tmp[i - 1];
  long long res = 0, sth;
  for (int j = 0; j <= 9; j++)
    if (j != a[p]) {
      sth = LLONG_MAX;
      for (int k = 9; ~k; k--)
        if (c[p][(a[p] + k) % 10] != c[p][(j + k) % 10]) sth = k;
      for (int i = p + 1; i <= n; i++)
        for (int k = 0; k <= 9; k++)
          if (c[i][(a[i] + k) % 10] != c[i][(a[i] + k + 1) % 10]) {
            sth = min(sth, (k + 1) * _k[i - p] - tmp[i - 1] - max(0, j - a[p]));
            break;
          }
      res = max(sth, res);
    }
  return res;
}
void solve() {
  scanf("%d", &n);
  for (int i = n - 1; ~i; i--) scanf("%1d", &a[i]);
  a[n] = 0, pre[0] = a[0];
  for (int i = 1; i <= n; i++) pre[i] = a[i] * _k[i] + pre[i - 1];
  for (int i = n - 1; ~i; i--) scanf("%s", c[i]);
  for (int i = 0; i < 10; i++) c[n][i] = 'a' + i;
  long long ans = 0;
  for (int i = 0; i < n; i++)
    ans = max(ans, calc(i) * _k[i] - (i ? pre[i - 1] : 0));
  printf("%lld\n", ans);
}
int main() {
  _k[0] = 1;
  for (int i = 1; i <= 19; i++) _k[i] = 10 * _k[i - 1];
  scanf("%d", &T);
  while (T--) solve();
}
