码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] N-Queens II

时间:2015-07-01 23:35:18      阅读:178      评论:0      收藏:0      [点我收藏+]

标签:

If you have solved the N-Queens problem, this one can be solved in a similar manner. Starting from the first row, we try each of its columns. If there is no attack, we move on to the next row based previous rows. Otherwise, we backtrack to the current row and try another selection of column position. Once we meet the last row, increase the counts by 1.

The code is as follows.

 1 class Solution {
 2 public:
 3     int totalNQueens(int n) {
 4         int* colPos = new int [n];
 5         int counts = 0;
 6         solve(colPos, n, 0, counts);
 7         delete colPos;
 8         return counts;
 9     }
10 private:
11     bool noAttack(int*& colPos, int row, int col) {
12         for (int r = row - 1, ld = col - 1, rd = col + 1; r >= 0; r--, ld--, rd++)
13             if (colPos[r] == col || colPos[r] == ld || colPos[r] == rd)
14                 return false;
15         return true;
16     }
17     void solve(int*& colPos, int n, int row, int& counts) {
18         if (row == n) {
19             counts++;
20             return;
21         }
22         for (int col = 0; col < n; col++) {
23             colPos[row] = col;
24             if (noAttack(colPos, row, col))
25                 solve(colPos, n, row + 1, counts);
26         }
27     }
28 };

Someone has even suggested a damn clever solution to this problem using bit-manipulations in this link (refer to the first answer).

I rewrite the code below for reference.

 1 class Solution {
 2 public:
 3     int totalNQueens(int n) {
 4         int counts = 0;
 5         int limit = (1 << n) - 1;
 6         solve(0, 0, 0, limit, counts);
 7         return counts;
 8     }
 9 private:
10     void solve(int hProj, int lProj, int rProj, int limit, int& counts) {
11         if (hProj == limit) {
12             counts++;
13             return;
14         }
15         int pos = limit & (~(hProj | lProj | rProj));
16         while (pos) {
17             int p = pos & (-pos);
18             pos ^= p;
19             solve(hProj | p, (lProj | p) >> 1, (rProj | p) << 1, limit, counts);
20         }
21     }
22 };

 

[LeetCode] N-Queens II

标签:

原文地址:http://www.cnblogs.com/jcliBlogger/p/4614716.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!