class Solution {
public:
/**
* @param n: The number of queens.
* @return: The total number of distinct solutions.
*/bool canPlaceQ(int row,int col, int * position,int n)
{
for (int i=0;i<row;i++)
{
if (position[i]==col||abs(row-i)==abs(col-position[i]))
{
returnfalse;
}
}
returntrue;
}
void placeQ(int &count,int row,int *position,int n)
{
if (row==n)
{
++count;
}
else
{
for (int j=0;j<n;j++)
{
if (canPlaceQ(row,j,position,n))
{
position[row]=j;
placeQ(count,row+1,position,n);
}
}
}
}
int totalNQueens(int n)
{
int count=0;
if (n<=0)
{
return0;
}
int *position=newint[n];
for (int i=0;i<n;i++)
{
position[i]=-1;
}
int row=0;
placeQ(count,row,position,n);
return count;
}
};
2.非递归
AC代码:
class Solution {
public:
/**
* @param n: The number of queens.
* @return: The total number of distinct solutions.
*/bool canPlaceQ(int row,int col, int * position,int n)
{
for (int i=0;i<row;i++)
{
if (position[i]==col||abs(row-i)==abs(col-position[i]))
{
returnfalse;
}
}
returntrue;
}
void placeQ(int &count,int row,int *position,int n)
{
int i=0,j=0;
while(i<n)
{
while(j<n)
{
if (canPlaceQ(i,j,position,n))
{
position[i]=j;
j=0;
break;
}
else
{
++j;
}
}
if (position[i]==-1)
{
if (i==0)
{
break;
}
--i;
j=position[i]+1;
position[i]=-1;//注意清空上一行的位置!!;continue;
}
if (i==n-1)
{
++count;
j=position[i]+1;//不能用++j,因为寻找到n-1行的列位置后j被重置为0;
position[i]=-1;
continue;
}
++i;
}
}
int totalNQueens(int n)
{
int count=0;
if (n<=0)
{
return0;
}
int *position=newint[n];
for (int i=0;i<n;i++)
{
position[i]=-1;
}
int row=0;
placeQ(count,row,position,n);
return count;
}
};