题目描述:
Follow up for N-Queens problem.
Now, instead outputting board configurations,
return the total number of distinct solutions.
思路:同N Queens一样,是一道题求的结果不同。
public class N_QueensTwo {
public static int count=0;
public static int solveNQueens(int n)
{
String board[][]=new String[n][n];
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
board[i][j]=".";
}
}
solve(board,n,0);
return count;
}
public static void solve(String board[][],int n,int line)
{
if(line==n)
{
count++;
}
else
{
//对每一行的每一列进行枚举
for(int i=0;i<n;i++)
{
if(check(board,n,line,i))
{
board[line][i]="Q";
}
else
{
continue;
}
solve(board,n,line+1);
board[line][i]=".";
}
}
}
public static boolean check(String board[][],int n,int line,int column)
{
for(int i=line-1;i>=0;i--)
{
if(board[i][column].equals("Q"))
{
return false;
}
}
for(int i=line-1,j=column-1;i>=0&&j>=0;i--,j--)
{
if(board[i][j].equals("Q"))
{
return false;
}
}
for(int i=line-1,j=column+1;i>=0&&j<n;i--,j++)
{
if(board[i][j].equals("Q"))
{
return false;
}
}
return true;
}
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
System.out.println(solveNQueens(n));
}
}