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.."] ]题意:N皇后问题。
思路:利用回溯做,一行一行的去放,所以我们只要判断列和对角线是否已经存在皇后就行了,当然也可以用标记数组做。
class Solution {
public:
bool isVaild(vector<string> tmp, int row, int col) {
for (int i = 0; i < tmp.size(); i++)
if (tmp[i][col] == 'Q')
return false;
for (int i = row-1, j = col-1; i >= 0 && j >= 0; i--, j--)
if (tmp[i][j] == 'Q')
return false;
for (int i = row-1, j = col+1; i >= 0 && j < tmp.size(); i--, j++)
if (tmp[i][j] == 'Q')
return false;
return true;
}
void dfs(vector<vector<string> > &ans, vector<string> &tmp, int cur) {
if (cur == tmp.size()) {
ans.push_back(tmp);
return;
}
for (int i = 0; i < tmp.size(); i++) {
if (isVaild(tmp, cur, i)) {
tmp[cur][i] = 'Q';
dfs(ans, tmp, cur+1);
tmp[cur][i] = '.';
}
}
}
vector<vector<string> > solveNQueens(int n) {
vector<vector<string> > ans;
vector<string> tmp(n, string(n, '.'));
dfs(ans, tmp, 0);
return ans;
}
};
原文:http://blog.csdn.net/u011345136/article/details/44177413