标签:
Follow up for N-Queens problem.
Now, instead outputting board configurations, return the total number of distinct solutions.
[Solution]
1 int totalNQueens(int n) 2 { 3 int solutions = 0; 4 if (n <= 0) 5 return solutions; 6 vector<int> mark(n, 0); 7 8 NQueen(mark, n, 0, solutions); 9 return solutions; 10 } 11 12 void NQueen(vector<int> &mark, int n, int row, int &solutions) 13 { 14 if (row == n) 15 { 16 solutions++; 17 return; 18 } 19 20 for (int i = 0; i < n; i++) 21 { 22 mark[row] = i; 23 if (check(mark, row)) 24 NQueen(mark, n, row + 1, solutions); 25 } 26 } 27 28 bool check(vector<int> mark, int row) 29 { 30 for (int i = 0; i < row; i++) 31 if (mark[row] == mark[i] || abs(mark[row] - mark[i]) == (row - i)) 32 return false; 33 return true; 34 }
标签:
原文地址:http://www.cnblogs.com/ym65536/p/4321658.html