#include <iostream> #include <fstream> #include <algorithm> using namespace std;
const int MAX = 50;
int n; BOOL Board[max][max]; BOARD[I][J] Record shape I, the color of J gems have been used int A[max][max]; Storage gem shape matrix int B[max][max]; Stores the gem color matrix bool OK (int r, int c, int k, bool Isshap) {if (ISSHAP)///Examine whether the current column has the same shape as the gem {for (int i=1; i< ; R;
i++) {if (a[i][c] = = k) return false;
}} else//Examine whether the current column has the same color of the gem {if (Board[a[r][c]][b[r][c]]) return false;
for (int i=1; i<r; i++) {if (b[i][c] = = k) return false;
}} return true; } long int num = 0; The number of different gem permutations//from top to bottom, left to right recursive search, that is, the first column void backtrack (int r, int c) {for (int i=c; i<=n; i++)//column if (OK (r, C,
A[r][i], true)//Examine whether the current column has the same shape of the gem {swap (a[r][c], a[r][i]); for (int j=c; j<=n; J + +) if (ok (r, c, B[r][j], false))//Examine whether the current column has the sameColored Gems {swap (b[r][c], b[r][j]);
board[A[r][c] [b[r][c]] = true; if (c = = N)//If the column is completed {if (r = = N)//If the line is completed num++
; else Backtrack (r+1, 1); Examine the next line} else Backtrack (r, c+1);
Examine the next list of swaps (B[r][c], b[r][j]);
board[A[r][c] [b[r][c]] = false;
} swap (A[r][c], a[r][i]);
}} int main () {ifstream fin ("Arrange gem. txt");
cout << "\ n input positive integer n:"; Fin >> N;
cout << n << Endl;
int I, J;
For (I=1, i<=n; i++) {for (j=1; j<=n; J + +) {Board[i][j] = false;
A[I][J] = j;
B[I][J] = j;
}} backtrack (1, 1); cout << "\ n different number of gem permutations:" << nUm
cout << Endl << Endl;
return 0;
}