题目:
Follow up for N-Queens problem.
Now, instead outputting board configurations, return the total number of distinct solutions.
题意:
接上题N-Queens problem,这里只是要求返回所有的不同的解的数目。
算法分析:
思路与上题相同,代码比上题更加简洁了
AC代码:
<span style="font-size:12px;">public class Solution
{
private int res=0;
public int totalNQueens(int n)
{
int[] loc = new int[n]; //记录皇后处于哪一列,列数组
dfs(loc,0,n);
return res;
}
public void dfs(int[] loc, int cur, int n)
{
if(cur==n)
res++;
else
{
for(int i=0;i<n;i++)
{
loc[cur] = i;
if(isValid(loc,cur))
dfs(loc,cur+1,n); //再放皇后m+1, 如果皇后m+1放完并返回了
//两种可能: 1:冲突,返回了 2.一直将所有的皇后全部放完并安全返回了
//将皇后m回溯,探索新的可能或者安全的位置 --->
}
}
}
public boolean isValid(int[] loc, int cur)
{
for(int i=0;i<cur;i++)//只需要保证与那些已经就位的皇后不冲突即可
{
if(loc[i]==loc[cur]||Math.abs(loc[i]-loc[cur])==(cur-i)) //验证对角线,根据对角线性质,长 = 宽
//那么我们不难写出 Math.abs(loc[i] - loc[cur]) == (cur - i)
return false;
}
return true;
}
}</span>