#include <string>
#include <iostream>
using namespace std;
string s[5][5]; char t[5][5][8]; int tc, n, m1, m2, z, a[27], b[27];
int main() {
	while (cin >> n, n) {
		for (int i = 0; i < 5; i++) {
			for (int j = 0; j < 5; j++) {
				cin >> s[i][j];
			}
		}
		cin >> m1; fill(a, a + 27, 0); for (int i = 0; i < m1; i++) cin >> z, a[z] = 1;
		cin >> m2; fill(b, b + 27, 0); for (int i = 0; i < m2; i++) cin >> z, b[z] = 1;
		for (int i = 0; i < n; i++) {
			for (int j = 0; j < 5; j++) {
				for (int k = 0; k < 5; k++) {
					for (int l = 0; l < 5; l++) {
						int cnt = 0;
						for (int v1 = -1; v1 <= 1; v1++) {
							for (int v2 = -1; v2 <= 1; v2++) {
								for (int v3 = -1; v3 <= 1; v3++) {
									int r1 = j + v1, r2 = k + v2, r3 = l + v3;
									if (!v1 && !v2 && !v3) continue;
									if (0 <= r1 && r1 < 5 && 0 <= r2 && r2 < 5 && 0 <= r3 && r3 < 5) {
										if (s[r1][r2][r3] == '1') cnt++;
									}
								}
							}
						}
						if (s[j][k][l] == '0') t[j][k][l] = a[cnt] + 48;
						else t[j][k][l] = b[cnt] + 48;
					}
				}
			}
			for (int j = 0; j < 5; j++) {
				for (int k = 0; k < 5; k++) {
					s[j][k] = t[j][k];
				}
			}
		}
		if (tc++) cout << endl;
		cout << "Case " << tc << ":" << endl;
		for (int i = 0; i < 5; i++) {
			if (i) cout << endl;
			for (int j = 0; j < 5; j++) {
				cout << s[i][j] << endl;
			}
		}
	}
	return 0;
}