# leetcode N-Queens II

### N-Queens II

Total Accepted: 1560 Total Submissions: 6035

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

The code similar to I is TLE

class Solution {
public:
bool check(vector<vector<int>>& board, int x, int y) {
int size = board.size(), xx, yy;
for (int i = 0; i < x; ++i)
if (board[i][y])
return false;
for (int i = 0; i < size; ++i)
if (board[x][i])
return false;
for (xx = --x, yy = --y; xx >= 0 && yy >= 0; --xx, --yy)
if (board[xx][yy])
return false;
for (xx = --x, yy = ++y; xx >= 0 && yy < size; --xx, ++yy)
if (board[xx][yy])
return false;
return true;
}
void dfs(vector<vector<int>>& board, int& count, int start) {
int size = board.size();
if (start == board.size()) {
++count;
return;
}
for (int i = 0; i < size; ++i) {
if (check(board, start, i)) {
board[start][i] = 1;
dfs(board, count, start + 1);
board[start][i] = 0;
}
}
}
int totalNQueens(int n) {
if (n == 0)
return 0;
int res = 0;
vector<vector<int>> board(n, vector<int>(n, 0));
dfs(board, res, 0);
return res;
}
};
The main problem is that the check function wastes too much time.

Two ways to avoid this:

1. Use an array to record the position row[i] , col[i](true, false)

2. BIt manipulation

class Solution {
public:
unsigned int upperlimit;
void dfs(int& count, unsigned int row, unsigned int ld, unsigned int rd) {
if (row == upperlimit)
++count;
unsigned int pos = (row | ld | rd) & upperlimit; // the bit 1 simplify the position can't place the queue any more
unsigned int p = (~pos) & upperlimit,digit = 0;
while (p) {
digit = p - (p & (p - 1)); // Find the rightest 1
//digit = p&(~p + 1);
dfs(count, row + digit, (ld + digit) >> 1, (rd + digit) << 1);
p -= digit;
}
}
int totalNQueens(int n) {
upperlimit = 0;
int count = 0;
for (int i = 0; i < n; ++i)
upperlimit |= (1<<i);
dfs(count, 0, 0, 0);
return count;
}
};

This is a WA code, find the problem!!!!!!

class Solution {
public:
unsigned int upperlimit;
int res = 0;
void dfs(unsigned int row, unsigned int ld, unsigned int rd) {
if (row == upperlimit)
++res;
unsigned int pos = (row | ld | rd) & upperlimit, p = (~pos) & upperlimit, digit;
while (p) {
digit = p - p & (p - 1);
dfs(row + digit, (ld + digit) << 1, (rd + digit) >> 1);
p -= digit;
}
};
int totalNQueens(int n) {
for (int i = 0; i < n; ++i)
upperlimit |= (1 << i);
res = 0;
dfs(0, 0, 0);
return res;
}
};

• 本文已收录于以下专栏：

举报原因： 您举报文章：leetcode N-Queens II 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)