LeetCode N & N Queen Queen II

Topic links: https://leetcode-cn.com/problems/n-queens/

Topic links: https://leetcode-cn.com/problems/n-queens-ii/

Subject to the effect:

  slightly.

analysis:

code show as below:

 1 class Solution {
 2 public:
 3     int allOne;
 4     vector<vector<string>> ans;
 5     vector<string> ret;
 6     string tmp;
 7     int N;
 8     
 9     vector<vector<string>> solveNQueens(int n) {
10         allOne = (1 << n) - 1;
11         ans.clear();
12         tmp.assign(n, '.');
 13 is          ret.assign (n-, tmp);
 14          N = n-;
 15          
16          Solve ( 0 , 0 , 0 , 0 );
 . 17          
18 is          return ANS;
 . 19      }
 20 is      
21 is      // VD: vertical direction
 22 is      // LD : left diagonal direction
 23 is      // RD: right diagonal direction 
24      void Solve ( int Level, int VD, int LD, int RD) {
 25          IF (Level == N) {
26             ans.push_back(ret);
27             return;
28         }
29         
30         int limit = (vd | ld | rd) ^ allOne;
31         int pos;
32         
33         while(limit) {
34             pos = lowbit(limit);
35             limit = cutLowbit(limit);
36             
37             ret[level][N - __builtin_ffs(pos)] = 'Q';
38             solve(level + 1, vd | pos, ((ld | pos) >> 1) & allOne, ((rd | pos) << 1) & allOne);
39             ret[level][N - __builtin_ffs(pos)] = '.';
40         }
41     }
42     
43     int lowbit(int x) {
44         return x & (-x);
45     }
46     
47     int cutLowbit(int x) {
48         return x & (x - 1);
49     }
50 };
View Code
 1 class Solution {
 2 public:
 3     int allOne;
 4     int ans;
 5     int N;
 6     
 7     int totalNQueens(int n) {
 8         allOne = (1 << n) - 1;
 9         ans = 0;
10         N = n;
11         
12         solve(0, 0, 0, 0);
13         
14         return ans;
15      }
 16      
. 17      // VD: vertical direction
 18 is      // LD: left diagonal directions
 . 19      // RD: right diagonal direction 
20 is      void Solve ( int Level, int VD, int LD, int RD) {
 21 is          IF (Level == N) {
 22 is              ++ ANS;
 23 is              return ;
 24          }
 25          
26 is          int limit = (VD | LD | RD) ^ allone;
 27          int POS;
 28          
29          the while (limit) {
30             pos = lowbit(limit);
31             limit = cutLowbit(limit);
32             
33             solve(level + 1, vd | pos, ((ld | pos) >> 1) & allOne, ((rd | pos) << 1) & allOne);
34         }
35     }
36     
37     int lowbit(int x) {
38         return x & (-x);
39     }
40     
41     int cutLowbit(int x) {
42         return x & (x - 1);
43     }
44 };
View Code

 

Guess you like

Origin www.cnblogs.com/zaq19970105/p/11410040.html