#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <set>
using namespace std;

int
main (
  int   argc,
  char *argv[ ]
  )
{
  int i, j, k, l, m, n;
  int c;

  for ( c = 1; ; ++c )
  {
    int d[ 5 ][ 5 ][ 5 ];
    set<int> a;
    set<int> b;
    int N;

    scanf ( "%d", &N );
    if ( N == 0 ) break ;
    for ( i = 0; i < 5; ++i )
    for ( j = 0; j < 5; ++j )
    {
      scanf ( "%d", &d[ i ][ j ][ 4 ] );
      d[ i ][ j ][ 0 ] = ( d[ i ][ j ][ 4 ] / 10000 ) % 10;
      d[ i ][ j ][ 1 ] = ( d[ i ][ j ][ 4 ] / 1000 ) % 10;
      d[ i ][ j ][ 2 ] = ( d[ i ][ j ][ 4 ] / 100 ) % 10;
      d[ i ][ j ][ 3 ] = ( d[ i ][ j ][ 4 ] / 10 ) % 10;
      d[ i ][ j ][ 4 ] = ( d[ i ][ j ][ 4 ] / 1 ) % 10;
    }
    scanf ( "%d", &m );
    for ( i = 0; i < m; ++i )
    {
      int d;
      scanf ( "%d", &d );
      a.insert ( d );
    }
    scanf ( "%d", &m );
    for ( i = 0; i < m; ++i )
    {
      int d;
      scanf ( "%d", &d );
      b.insert ( d );
    }

    while ( N-- )
    {
      int r[ 5 ][ 5 ][ 5 ] = { 0 };

      for ( i = 0; i < 5; ++i )
      for ( j = 0; j < 5; ++j )
      for ( k = 0; k < 5; ++k )
      {
        for ( l = max ( 0, i - 1 ); l < min ( 5, i + 2 ); ++l )
        for ( m = max ( 0, j - 1 ); m < min ( 5, j + 2 ); ++m )
        for ( n = max ( 0, k - 1 ); n < min ( 5, k + 2 ); ++n )
        {
          if ( l == i && m == j && n == k ) continue ;
          r[ i ][ j ][ k ] += d[ l ][ m ][ n ];
        }
      }

      for ( i = 0; i < 5; ++i )
      for ( j = 0; j < 5; ++j )
      for ( k = 0; k < 5; ++k )
      {
        if ( d[ i ][ j ][ k ] )
        {
          if ( b.find ( r[ i ][ j ][ k ] ) == b.end ( ) )
            d[ i ][ j ][ k ] = 0;
        }
        else
        {
          if ( a.find ( r[ i ][ j ][ k ] ) != a.end ( ) )
            d[ i ][ j ][ k ] = 1;
        }
      }
    }

    if ( c != 1 ) puts ( "" );
    printf ( "Case %d:\n", c );
    for ( i = 0; i < 5; ++i )
    {
      if ( i ) puts ( "" );
      for ( j = 0; j < 5; ++j )
      {
        for ( k = 0; k < 5; ++k )
          printf ( "%d", d[ i ][ j ][ k ] );
        puts ( "" );
      }
    }
  }

  return ( EXIT_SUCCESS );
}