#include #include #include #include #include #include #include #include using namespace std; typedef pair PII; set T; vector V; int cnt, M, N, K, poc, chyba; //rieseni, rozmery, tehliciek, doteraz doplnenych, celkovo na doplnenie void skus(int x, int y){ //cout << x << " " << y << endl; if (y < N-1){ PII pom = PII(min(V[x][y], V[x][y+1]), max(V[x][y], V[x][y+1])); if (T.find(pom) != T.end()){ //cout << "vodorovna " << (char)pom.first << " " << (char)pom.second << endl; T.erase(pom); char xy = V[x][y]; V[x][y] = '['; char yx = V[x][y+1]; V[x][y+1] = ']'; poc += 2; if (poc == chyba) { if (!cnt++) for (int i = 0; i < M; i++) cout << V[i] << endl; } else for (int i = 0; i < M*N; i++){ //cout << " " << V[i/N][i%N] << isdigit(V[i/N][i%N]) << endl; if(isdigit(V[i/N][i%N])) { skus(i/N, i%N); break; } } V[x][y] = xy; V[x][y+1] = yx; T.insert(pom); poc -= 2; } } if (x < M-1){ PII pom = PII(min(V[x][y], V[x+1][y]), max(V[x][y], V[x+1][y])); if (T.find(pom) != T.end()){ //cout << "zvisla " << (char)pom.first << " " << (char)pom.second << endl; T.erase(pom); char xy = V[x][y]; V[x][y] = 'n'; char yx = V[x+1][y]; V[x+1][y] = 'u'; poc += 2; if (poc == chyba){ if (!cnt++) for (int i = 0; i < M; i++) cout << V[i] << endl; } else for (int i = 0; i < M*N; i++) if(isdigit(V[i/N][i%N])) { skus(i/N, i%N); break; } V[x][y] = xy; V[x+1][y] = yx; T.insert(pom); poc -= 2; } } } int main(void){ while(8){ scanf("%d %d %d", &M, &N, &K); if (M == 0) break; V.resize(0); V.resize(M+47); T.clear(); for (int i = 0; i < K; i++){ char a, b; scanf(" %c %c", &a, &b); T.insert(PII(min(a, b), max(a, b))); } chyba = 0; for (int i = 0; i < M; i++){ for (int j = 0; j < N; j++){ char c; scanf(" %c", &c); V[i] += c; if (c != 'X') chyba++; } } if (!chyba) { for (int i = 0; i < M; ++i) cout << V[i] << endl; cout << 0 << endl << endl; continue; } //for (int i = 0; i < M; i++) cout << V[i] << endl; //for (set::iterator it = T.begin(); it != T.end(); it++) cout << (char)(it -> first) << " " << (char)(it -> second) << endl; cnt = poc = 0; skus(0, 0); if (cnt == 0) cout << "impossible" << endl << endl; else{ cout << cnt-1 << endl << endl; } } }