您的位置:首页 > 产品设计 > UI/UE

[LeetCode] N-Queens

2015-07-01 21:16 573 查看
The idea is to use backtracking. In fact, the code below uses DFS, which involves backtracking in a recursive manner.

The idea is also very simple. Starting from the first row, try each column. If it does not induce any attack, move on to the next row based on the configurations of the previous rows. Otherwise, backtrack to the current row and try another selection of the column position. Once we reach the last row, add the current setting to a vector<vector<string> >.

The code below is referenced to this link, which records the positions of the queens using a nice 1d array like a[row] = col to indicate there is a queen at (row, col).

The code is as follows.

class Solution {
public:
vector<vector<string>> solveNQueens(int n) {
vector<vector<string> > queens;
vector<int> colPos(n, 0);
solve(colPos, n, 0, queens);
return queens;
}
private:
bool noAttack(vector<int>& colPos, int row, int col) {
for (int r = row - 1, ld = col - 1, rd = col + 1; r >= 0; r--, ld--, rd++)
if (colPos[r] == col || colPos[r] == ld || colPos[r] == rd)
return false;
return true;
}
vector<string> queenStr(vector<int>& colPos) {
int n = colPos.size();
vector<string> queen(n, string(n, '.'));
for (int i = 0; i < n; i++)
queen[i][colPos[i]] = 'Q';
return queen;
}
void solve(vector<int>& colPos, int n, int row, vector<vector<string> >& queens) {
if (row == n) {
queens.push_back(queenStr(colPos));
return;
}
for (int col = 0; col < n; col++) {
colPos[row] = col;
if (noAttack(colPos, row, col))
solve(colPos, n, row + 1, queens);
}
}
};


Well, if you have solved N-Queens II, you may know that problem has a nice bit-manipulation solution (you may refer to this passage). In fact, that bit-manipulation idea can also be used to solve this problem. The code is as follows.

class Solution {
public:
vector<vector<string>> solveNQueens(int n) {
vector<vector<string> > queens;
vector<string> queen;
int limit = (1 << n) - 1;
solve(0, 0, 0, n, limit, queen, queens);
return queens;
}
private:
void solve(int hProj, int lProj, int rProj, int n, int limit, vector<string>& queen, vector<vector<string> >& queens) {
if (hProj == limit) {
queens.push_back(queen);
return;
}
int pos = ~(hProj | lProj | rProj);
for (int i = 0; i < n; i++) {
int p = (1 << i);
if (pos & p) {
string line(n ,'.');
line[i] = 'Q';
queen.push_back(line);
solve(hProj | p, (lProj | p) << 1, (rProj | p) >> 1, n, limit, queen, queens);
queen.pop_back();
}
}
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: