1. 程式人生 > >力扣算法題—052N皇後問題2

力扣算法題—052N皇後問題2

回溯 code row true return pub || nqueens ger

跟前面的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 }

力扣算法題—052N皇後問題2