N-Queens II

Follow up for N-Queens problem.

Now, instead outputting board configurations, return the total number of distinct solutions.

C++:
01 void solve(vector<int>& cur, int n, int& cnt)
02 {
03     int m=cur.size();
04     if(m==n){
05         cnt++;
06         return;
07     }
08     int* table=new int[n];
09     for(int i=0;i<n;i++)
10         table[i]=0;
11     for(int i=0;i<m;i++){
12         int k=cur[i];
13         table[k]=1;
14         int left=k(mi);
15         int right=k+mi;
16         if(left>=0)
17             table[left]=1;
18         if(right<n)
19             table[right]=1;
20 
21     }
22     for(int i=0;i<n;i++){
23         if(table[i]==0){
24             cur.push_back(i);
25             solve(cur, n, cnt);
26             cur.pop_back();
27         }
28     }
29     delete []table;
30 }
31 
32 int totalNQueens(int n) {
33     vector<int> cur;
34     int cnt=0;
35     solve(cur, n, cnt);
36     return cnt;
37 }
Advertisements
This entry was posted in Array and linked list, Backtrack. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s