首页 > 其他 > 详细

[LeetCode] N-Queens II

时间:2015-07-01 23:34:21      阅读:311      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!