#include <bits/stdc++.h>
using namespace std;
int main() {
  long long int t;
  cin >> t;
  long long int n;
  long long int a[20];
  long long int W[20];
  long long int T[20];
  long long int D[20];
  char c[20][10];
  string s;
  for (int i = 0; i < t; ++i) {
    cin >> n;
    cin >> s;
    int _j = 0;
    for (int j = n - 1; j >= 0; --j) {
      a[_j] = s[j] - '0';
      _j++;
    }
    for (int j = n - 1; j >= 0; --j) {
      cin >> s;
      for (int k = 0; k < 10; ++k) {
        c[j][k] = s[k];
      }
    }
    T[n] = 1;
    for (int j = n - 1; j >= 0; --j) {
      int y = 0;
      if (j == n - 1) {
        y = 1;
      } else {
        while (c[j + 1][a[j + 1]] == c[j + 1][(a[j + 1] + y) % 10] && y < 10) {
          y++;
        }
      }
      if (y == 10) {
        T[j] = 10 - a[j] + (T[j + 1] - 1) * 10;
      } else {
        T[j] = min(10 - a[j] + (y - 1) * 10, 10 - a[j] + (T[j + 1] - 1) * 10);
      }
    }
    for (int j = 0; j < n; ++j) {
      long long int k;
      W[j] = -1;
      for (long long int l = 1; l < 10; ++l) {
        for (k = 0; k < 10; ++k) {
          if (c[j][(a[j] + k) % 10] != c[j][(a[j] + l + k) % 10]) {
            break;
          }
        }
        if (k == 10) {
          if ((a[j] + l) % 10 < a[j]) {
            W[j] = max(W[j], T[j]);
          } else {
            W[j] = max(W[j], T[j] - l);
          }
        } else {
          if ((a[j] + l) % 10 < a[j]) {
            W[j] = max(W[j], min(k, T[j]));
          } else {
            W[j] = max(W[j], min(k, T[j] - l));
          }
        }
      }
    }
    for (int j = n - 1; j >= 0; --j) {
      D[j] = min(W[j], T[j]);
      if (W[j] == -1) {
        D[j] = T[j];
      }
    }
    long long int A = 0, Q = 1;
    for (int j = 0; j < n; ++j) {
      if (D[j] != 0) {
        D[j] = D[j] * Q - A;
      }
      if (j > 0) {
        D[j] = max(D[j], D[j - 1]);
      }
      A = a[j] * Q + A;
      Q *= 10;
    }
    cout << D[n - 1] << endl;
  }
}
