标签:
Follow up for N-Queens problem.
Now, instead outputting board configurations, return the total number of distinct solutions.
问题是求N皇后的解,可以采用回溯法解决。
1 class Solution { 2 public: 3 4 bool isSafe(vector<int> &A,int r){ 5 for(int i=0;i<r;i++){ 6 if((A[i]==A[r])||(abs(A[i]-A[r]))==(r-i)) 7 return false; 8 } 9 return true; 10 } 11 12 void queen(int n,int &result,int cur,vector<int> &A){ 13 if(cur==n){ 14 result++; 15 return ; 16 }else{ 17 for(int i=0;i<n;i++){ 18 A[cur]=i; 19 if(isSafe(A,cur)) 20 queen(n,result,cur+1,A); 21 } 22 } 23 } 24 25 int totalNQueens(int n) { 26 int result=0; 27 vector<int> A(n,-1); 28 queen(n,result,0,A); 29 return result; 30 } 31 };
标签:
原文地址:http://www.cnblogs.com/jawiezhu/p/4437027.html