class Solution {
public:
int a[100];
bool issuit(int a[], int n, int row, int col)//判断是否适合放置
{
for (int i = 0; i < row; i++)
{
if (abs(a[i] - col) == abs(row - i) || col == a[i])
return false;
}
return true;
}
void dfs(int row, int n, string str, vector<string> &vec,vector<vector<string>>& vecvec)
{
if (n == row)
{
vecvec.push_back(vec);
//vec.pop_back();
//vec.clear();
}
for (int i = 0; i < n; i++)
{
if (issuit(a, n, row, i))
{
a[row] = i;
str[i] = 'Q';
vec.push_back(str);
str[i] = '.';
dfs(row + 1, n, str,vec, vecvec);
vec.pop_back();
}
}
}
vector<vector<string>> solveNQueens(int n) {
vector<vector<string>> vecvec;
vector<string> vec;
string str = "";
for (int i = 0; i < n; i++)
{
str.append(".");
}
dfs(0, n, str,vec, vecvec);
return vecvec;
}
};
leetcode 八皇后问题
最新推荐文章于 2023-10-13 21:38:30 发布