//A New Growth Industry
//细菌培养基
#include<iostream>
using namespace std;
int shu[25][25],guodu[25][25];
int d[16];
int main()
{
int n,i,j,tianshu,temp;
cin>>n;
while(n--)
{
memset(shu,0,sizeof(shu));
memset(guodu,0,sizeof(guodu));
cin>>tianshu;
for(i=0;i<16;i++)
cin>>d[i];
for(i=1;i<=20;i++)
for(j=1;j<=20;j++)
cin>>shu[i][j];
while(tianshu--)
{
for(i=1;i<=20;i++)
for(j=1;j<=20;j++)
{
temp=shu[i][j]+shu[i+1][j]+shu[i][j+1]+shu[i-1][j]+shu[i][j-1];
if(shu[i][j]+d[temp]>3)
guodu[i][j]=3;
else if(shu[i][j]+d[temp]<0)
guodu[i][j]=0;
else
guodu[i][j]=shu[i][j]+d[temp];
}
for(i=1;i<=20;i++)
for(j=1;j<=20;j++)
shu[i][j]=guodu[i][j];
}
for(i=1;i<=20;i++)
{
for(j=1;j<=20;j++)
{
switch(shu[i][j])
{
case 0:
cout<<".";
break;
case 1:
cout<<"!";
break;
case 2:
cout<<"X";
break;
case 3:
cout<<"#";
break;
}
}
cout<<endl;
}
if(n)
cout<<endl;
}
return 0;
}