N-Queens II

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.."]
]

Solution: 1. Recursion.
2. Recursion + bit version. (fast)
The idea is from http://www.matrix67.com/blog/archives/266 (in chinese).
3. Iteration.

 1 class Solution {
 2 public:
 3     int totalNQueens(int n) {
 4         int res = 0;
 5         totalNQueensRe(n, 0, 0, 0, res);
 6         return res;
 7     }
 8     
 9     void totalNQueensRe(int n, int row, int ld, int rd, int &total)
10     {
11         if(row == (1 << n) - 1) {
12             total++;
13             return;
14         }
15         
16         int valid = ~(row | ld | rd);
17         for(int i = n - 1; i >= 0; --i) {
18             int pos = 1 << i;
19             if (valid & pos)
20                 totalNQueensRe(n, row | pos, (ld | pos) << 1, (rd | pos) >> 1, total);
21         }
22     }
23 };

 

posted @ 2014-04-11 10:30  beehard  阅读(122)  评论(0编辑  收藏  举报