# java实现 HDU 2553 n皇后解的数量

Input

Output

Sample Input
1
8
5
0

Sample Output
1
92
10

import java.util.Scanner;

public class n皇后的解的数量 {

private static final int MAXNUM = 15;
private static int n = 0;
private static int cnt = 0;
private static int[][] chess = new int [MAXNUM][MAXNUM];
private static int[] ans = new int [MAXNUM];

public static void main(String[] args) {
//存数组里，否则会超时
for(n = 1; n <= 10; n++){
cnt = 0;
solve(0);
ans[n] = cnt;
}
Scanner scan = new Scanner(System.in);
while((n = scan.nextInt())!=0){
System.out.println(ans[n]);
}
scan.close();
}

public static void solve(int row) {
if(row == n) {
cnt++;
return ;
}
for(int i = 0; i < n; i++) {
if(valid(row, i)) {
chess[row][i] = 1;
solve(row + 1);
chess[row][i] = 0;
}
}
}

private static boolean valid(int row, int col) {
//上方是否有棋子
for (int i = 0; i < row; i++) {
if (chess[i][col] == 1) {
return false;
}
}
//右上是否有棋子
for (int i = row - 1, j = col + 1; i >= 0 && j < n; i--, j++) {
if (chess[i][j] == 1) {
return false;
}
}
//左上是否有棋子
for (int i = row - 1, j = col - 1; i >= 0 && j >= 0; i--, j--) {
if (chess[i][j] == 1) {
return false;
}
}
return true;
}
}


10-19 738
03-06 485
03-07 960
©️2020 CSDN 皮肤主题: 深蓝海洋 设计师:CSDN官方博客