目录
1.N皇后

对于N皇后这道题,可以用标志数组来表示这列,主对角线,副对角线是否能存放皇后,那么如何用一个通式来描述
我们发现每主对角线都符合y = x + b,所以可以写为y - x = b, 但是对于边界的几点例如(1,0)减出来为负数,所以可以统一加上皇后数n来保证正数,所以可以写为y - x + n = b + n,
而副对角线符合y = -x + b, 写为y + x = b即可
cpp
class Solution {
bool checkcol[10], checkdig1[20], checkdig2[20];
vector<vector<string>> ret;
vector<string> path;
int n;
public:
vector<vector<string>> solveNQueens(int _n)
{
n = _n;
path = vector<string>(n, string(n, '.'));
dfs(0);
return ret;
}
void dfs(int row)
{
if(row == n)
{
ret.push_back(path);
return;
}
for(int col = 0; col < n; col++)
{
if(checkcol[col] == false && checkdig1[row - col + n] == false && checkdig2[row + col] == false)
{
path[row][col] = 'Q';
checkcol[col] = checkdig1[row - col + n] = checkdig2[row + col] = true;
dfs(row + 1);
path[row][col] = '.';
checkcol[col] = checkdig1[row - col + n] = checkdig2[row + col] = false;
}
}
}
};