#include <bits/stdc++.h>
using namespace std;
long long gcd(long long a, long long b) { return b == 0 ? a : gcd(b, a % b); }
const int MAXN = 18;
int n;
char nr[MAXN + 1];
char g[MAXN][10 + 1];
void dbg() {
  printf("%d\n", n);
  printf("%s\n", nr);
  for (int j = (0); j < (10); ++j) printf("%s\n", g[j]);
}
long long calca(int at) {
  int dig = nr[at] - '0';
  int ret = 0;
  for (int i = (0); i < (10); ++i)
    if (i != dig) {
      int cur;
      for (cur = 0; cur < 10; ++cur)
        if (g[at][(dig + cur) % 10] != g[at][(i + cur) % 10]) break;
      if (cur == 10) return LLONG_MAX;
      if (cur > ret) ret = cur;
    }
  return ret;
}
long long calcb(int at) {
  int dig = nr[at] - '0';
  int ret = 0;
  for (int i = (0); i < (10); ++i)
    if (i != dig) {
      int cur;
      for (cur = 0; cur < 10; ++cur)
        if ((dig + cur >= 10 ? '$' : g[at][dig + cur]) !=
            (i + cur >= 10 ? '$' : g[at][i + cur]))
          break;
      assert(cur != 10);
      if (cur > ret) ret = cur;
    }
  return ret;
}
bool knowall(int at, long long incs, long long parincs) {
  int dig = nr[at] - '0';
  if (dig + incs >= 10 * parincs + 10) return true;
  for (int cur = 1; cur < 10 && cur <= incs; ++cur)
    if (g[at][(dig + cur) % 10] != g[at][dig]) return true;
  return false;
}
long long calc(int at, long long parincs) {
  if (at >= n) return parincs;
  int dig = nr[at] - '0';
  long long a = calca(at);
  long long b = calcb(at);
  long long incs = max(10 * parincs - dig, min(a, 10 * parincs + b));
  if (knowall(at, incs, parincs)) {
    long long ret = incs;
    for (int i = (at + 1); i < (n); ++i) ret = ret * 10 - (nr[i] - '0');
    return ret;
  } else {
    return calc(at + 1, incs);
  }
}
void run(int casenr) {
  scanf("%d", &n);
  scanf("%s", nr);
  for (int i = (0); i < (n); ++i) scanf("%s", g[i]);
  long long ret = calc(0, 0);
  printf("%lld\n", ret);
}
int main() {
  int n;
  scanf("%d", &n);
  for (int i = (1); i <= (n); ++i) run(i);
  return 0;
}
