import java.util.Scanner;
public class Main{
static int ans= 0;
static int n;
static int[][] board = new int[20][20];
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
dfs(0, n);
System.out.println(ans);
}
public static void dfs(int step,int n){
if(step == n){
ans++;
return;
}
for(int i = 0;i<n;i++){
if(isValid(step,i)){
board[step][i]++;
dfs(step+1, n);
board[step][i]--;
}
}
}
public static boolean isValid(int row, int col) {
// 检查列是否有皇后冲突
for (int i = 0; i < n; i++) {
if (board[i][col] > 0) {
return false;
}
}
// 检查右上方是否有皇后冲突
for (int i = row - 1, j = col + 1; i >=0 && j < n; i--, j++) {
if (board[i][j] > 0) {
return false;
}
}
// 检查左上方是否有皇后冲突
for (int i = row - 1, j = col - 1; i >= 0 && j >= 0; i--, j--) {
if (board[i][j] > 0) {
return false;
}
}
return true;
}
}
n皇后方案数——Java(DFS)
最新推荐文章于 2024-08-14 23:12:09 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)