II:

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 };

 

 

I:

The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.

 

Given an integer n, return all distinct solutions to the n-queens puzzle.

Each solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both indicate a queen and an empty space respectively.

For example,
There exist two distinct solutions to the 4-queens puzzle:

[
[".Q..", // Solution 1
"...Q",
"Q...",
"..Q."],

["..Q.", // Solution 2
"Q...",
"...Q",
".Q.."]
]

 

 1 class Solution {
 2 public:
 3     void printQueen(vector<int> &A,int n,vector<vector<string> >&res)
 4     {
 5         vector<string> r;
 6         for(int i=0;i<n;i++)
 7         {
 8             string str(n,'.');
 9             str[A[i]]='Q';
10             r.push_back(str);
11         }
12         res.push_back(r);
13     }
14     bool isValidQueens(vector<int>A,int r)
15     {
16         for(int i=0;i<r;i++)
17         {
18             if((A[i]==A[r])||(abs(A[i]-A[r]))==(r-i))
19                 return false;
20         }
21         return true;
22     }
23     void nqueens(vector<int> A,int cur,int n,vector<vector<string> >&res)
24     {
25         if(cur==n)
26         {
27             printQueen(A,n,res);
28         }else{
29             for(int i=0;i<n;i++)
30             {
31                 A[cur]=i;
32                 if(isValidQueens(A,cur))
33                     nqueens(A,cur+1,n,res);
34             }
35         }
36     }
37 
38     vector<vector<string> > solveNQueens(int n) {
39         vector<vector<string> >res;
40         res.clear();
41         vector<int> A(n,-1);
42         nqueens(A,0,n,res);
43         return res;
44     }
45 };

 

posted on 2015-04-18 16:56  黄瓜小肥皂  阅读(203)  评论(0编辑  收藏  举报