题目如下:
The n-queens puzzle is the problem of placing n queens on ann�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.
There exist two distinct solutions to the 4--queens puzzle:
[ [".Q..", // Solution 1 "...Q", "Q...", "..Q."], ["..Q.", // Solution 2 "Q...", "...Q", ".Q.."] ]
思路:先定义一个数组pArray[n],数组中第i个数字表示位于第i行的皇后的列号。先把pArray数组初始化,接下来我们要做的事情就是对数组pArray做全排列。由于我们是用不同的数字初始化数组中的数字,因此任意两个皇后肯定不同列。我们只需要判断得到的每一个排列对应的任意两个皇后是不是在同一对角斜线上,也就是数组的两个下标i和j,是不是i-j==pArray[i]pArray[j]或者j-i==pArray[i]-pArray[j]。
对于求出了一个正确的数组,就可以将此数组转化为矩阵了,这里需要利用到一个概念:一个n-皇后矩阵的转置还是n-皇后矩阵。具体证明很简单,我在这就不给出了。
void swap(int *p1,int *p2)
{int temp=*p1;
*p1=*p2;
*p2=temp;
}
bool Check(int *p,int n)
{
bool cheak = true;
for(int i=0;i<n-1;i++)
{
for(int j=i+1;j<n;j++)
{
if(((j-i)==(p[j]-p[i]))||((i-j)==(p[j]-p[i])))
{
cheak=false;
i=n;
break;
}
}
}
return cheak;
}
void FallArray(int *p,int n,int m,vector<vector<string> > &result)
{
if(m==n)
{
if(Check(p,n))
{
vector<string> tp;
for(int i=0;i<n;i++)
{
string temp;
for(int j=0;j<n;j++)
{
if(p[i]==j)temp+='Q';
else temp+='.';
}
tp.push_back(temp);
}
result.push_back(tp);
}
}
else
{
for(int i=m;i<n;i++)
{
swap(p+i,p+m);
FallArray(p,n,m+1,result);
swap(p+i,p+m);
}
}
}
vector<vector<string> > solveNQueens(int n)
{
vector<vector<string> > result;
if(n<=0) return result;
int *pArray=new int[n];
for(int i=0;i<n;i++)pArray[i]=i;
FallArray(pArray,n,0,result);
delete []pArray;
return result;
}