生成N皇后问题所有局面 N-Queens

时间:2023-02-06 11:06:38

Backtracking is a general algorithm for finding all (or some) solutions to some computational problem, that incrementally builds candidates to the solutions, and abandons each partial candidate c ("backtracks") as soon as it determines that c cannot possibly be completed to a valid solution.


代码:

class Solution {
public:
vector<vector<string> > boards; //所有盘面的集合

vector<vector<string> > solveNQueens(int n) {
boards.clear();
if(n == 0)
return boards;

int A[n];
memset(A, 0, sizeof(A));
queen(A, n, 0);
return boards;
}

void queen(int A[], int n, int row) //Backtrack
{
if(row == n)
{
boards.push_back(addone(A, n));
}
else
{
for(int i=0;i<n;i++)
if(isValid(A, n, row, i))
{
A[row] = i;
queen(A, n, row+1);
}
}
}

bool isValid(int A[], int n, int row, int col) //判定冲突
{
for(int i=0;i<row;i++)
{
if(A[i] == col)
return false;
if(abs(A[i] - col) == abs(i - row))
return false;
}
return true;
}

vector<string> addone(int A[], int n) //由一维数组形式生成盘面
{
vector<string> one;
for(int i=0;i<n;i++)
{
string tmp = "";
for(int j=0;j<n;j++)
if(A[i] != j)
tmp += '.';
else
tmp += 'Q';

one.push_back(tmp);
}
return one;
}

};