#include <bits/stdc++.h>
using namespace std;
int T, n, a[21];
long long P[21], b[21], b1[21], ans = 0;
char sc[21], c[21][21];
string sw[21];
set<string> mp;
inline long long calc(int x) {
  int i, j, k;
  long long res = 0, v;
  memset(b1, 0, sizeof(b1));
  for (i = x; i < n; i++) b1[i] = (i ? b1[i - 1] : 0) + a[i] * P[i - x];
  for (j = 0; j <= 9; j++)
    if (j != a[x]) {
      for (k = 0; k <= 9; k++)
        if (c[x][(a[x] + k) % 10] != c[x][(j + k) % 10]) break;
      v = (k <= 9) ? k : 0x3f3f3f3f3f3f3f3fll;
      for (i = x + 1; i < n; i++)
        for (k = 0; k <= 9; k++)
          if (c[i][(a[i] + k) % 10] != c[i][(a[i] + k + 1) % 10]) {
            v = min(v, (k + 1) * P[i - x] - b1[i - 1] + a[x] - max(a[x], j));
            break;
          }
      res = max(res, v);
    }
  return res;
}
int main() {
  P[0] = 1;
  for (int i = 1; i <= 19; i++) P[i] = 10ll * P[i - 1];
  scanf("%d", &T);
  while (T--) {
    scanf("%d", &n);
    int i;
    ans = 0;
    scanf("%s", sc);
    for (i = 0; i < n; i++) a[i] = sc[n - 1 - i] ^ 48;
    a[n++] = 0;
    b[0] = a[0];
    for (i = 1; i < n; i++) b[i] = b[i - 1] + P[i] * a[i];
    for (i = 0; i <= 9; i++) c[n - 1][i] = 'a' + i;
    for (i = n - 2; i >= 0; i--) scanf("%s", c[i]);
    for (i = 0; i < n - 1; i++)
      ans = max(ans, calc(i) * P[i] - (i ? b[i - 1] : 0));
    printf("%lld\n", ans);
  }
  return 0;
}
