/*
  [NWERC'06] SUDOKU
  by: Jan Kuipers
*/

using namespace std;

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>

int solfound;
vector<int> rowused,colused,row,col;
vector<int> mapab,mapba,mapdep;
vector<string> sol,sud;

void selectcol (int n) {
  
  if (n==9) solfound=1;
  if (solfound) return;
  
  int fr = n%3==0 ? 0 : col[n/3*3]/3*3;
  int to = n%3==0 ? 9 : fr+3;
  
  for (int i=fr; i<to; i++) 
    if (!colused[i]) {
      col[n]=i;
      colused[i]=1;

      int ok=1;
      for (int r=0; r<9; r++)
	if (sud[r][n]!='0') {
	  int a = sud[r][n]-'1';
	  int b = sol[row[r]][col[n]]-'1';

	  if (mapab[a]!=b && mapab[a]!=-1) ok=0;
	  if (mapba[b]!=a && mapba[b]!=-1) ok=0;

	  if (ok && mapdep[a]==-1) {
	    mapdep[a]=n;
	    mapab[a]=b;
	    mapba[b]=a;
	  }
	}
      
      if (ok) selectcol (n+1);

      for (int a=0; a<9; a++)
	if (mapdep[a]==n) {
	  mapdep[a]=-1;
	  mapba[mapab[a]]=-1;
	  mapab[a]=-1;
	}
      
      colused[i]=0;
    }
}

void selectrow (int n) {

  if (solfound) return;
  if (n==9) selectcol(0);
  
  int fr = n%3==0 ? 0 : row[n/3*3]/3*3;
  int to = n%3==0 ? 9 : fr+3;
  
  for (int i=fr; i<to; i++) 
    if (!rowused[i]) {
      row[n]=i;
      rowused[i]=1;
      selectrow (n+1);
      rowused[i]=0;
    }
}

void rotate () {
  vector<string> old=sud;
  
  for (int y=0; y<9; y++)
    for (int x=0; x<9; x++)
      sud[8-x][y]=old[y][x];
}

int main () {

  int runs;
  cin>>runs;
  while (runs--) {

    sol = sud = vector<string>(9);
    for (int i=0; i<9; i++) cin>>sol[i];
    for (int i=0; i<9; i++) cin>>sud[i];

    row=col=rowused=colused=vector<int>(9,0);
    mapab=mapba=mapdep=vector<int>(9,-1);
    solfound=0;
    
    selectrow(0);
    rotate();
    selectrow(0);
    
    cout << (solfound ? "Yes" : "No") << endl;
  }
  
  return 0;
}
