跟前面的N皇后问题没区别,还更简单
1 #include "000库函数.h" 2 3 //使用回溯法 4 class Solution { 5 public: 6 int totalNQueens(int n) { 7 int res = 0; 8 vector<int>x(n, -1);//标记 9 NQueue(x, res, 0); 10 return res; 11 } 12 13 void NQueue(vector<int>&x, int &num, int row) { 14 int n = x.size(); 15 if (n == row) 16 num++; 17 for (int col = 0; col < n; ++col) 18 if (Danger(x, row, col)) { 19 x[row] = col; 20 NQueue(x, num, row + 1); 21 x[row] = -1;//回溯 22 } 23 } 24 25 bool Danger(vector<int>x, int row, int col) { 26 for (int i = 0; i < row; ++i) 27 if (col == x[i] || abs(row - i) == abs(x[i] - col)) 28 //行列与斜边 29 return false; 30 return true; 31 } 32 }; 33 34 void T052() { 35 Solution s; 36 cout << s.totalNQueens(4) << endl; 37 cout << s.totalNQueens(8) << endl; 38 }