题目
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:
分析
一个经典N皇后问题,这种棋盘类的题目一般是回溯法, 依次放置每行的皇后。要求在放置的时候,要保持当前的状态为合法,即当前放置位置的同一行、同一列、两条对角线上都不存在皇后。
AC代码
class Solution {
private:
vector<vector<string> > ret;
public:
vector<vector<string>> solveNQueens(int n) {
if (n <= 0)
return vector<vector<string>>();
//二维字符矩阵,存储当前满足N皇后的解
vector<string> cur(n, string(n, '.'));
//调用主函数
set_queens(cur, 0);
return ret;
}
void set_queens(vector<string> &cur, int row)
{
int size = cur.size();
if (row == size)
{
ret.push_back(cur);
return;
}
else{
for (int col = 0; col < size; col++)
{
if (isValid(cur, row, col))
{
cur[row][col] = 'Q';
//安置下一个皇后
set_queens(cur, row + 1);
cur[row][col] = '.';
}//for
}//for
}
}
//判断在cur[row][col]位置放一个皇后,是否是合法的状态
//已经保证了每行一个皇后,只需要判断列是否合法以及对角线是否合法。
bool isValid(vector<string> &cur, int row, int col)
{
//判断是否同列
for (int i = 0; i < row; i++)
{
if (cur[i][col] == 'Q')
return false;
}//for
//判断是否同一左对角线
for (int i = row - 1, j = col - 1; i >= 0 && j >= 0; --i, --j)
{
if (cur[i][j] == 'Q')
return false;
}
//判断是否同一右对角线
for (int i = row - 1, j = col + 1; i >= 0 && j <= cur.size(); --i, ++j)
{
if (cur[i][j] == 'Q')
return false;
}
return true;
}
};