package 模拟题2021;
import java.util.Scanner;
// 1:无需package
// 2: 类名必须Main, 不可修改
/*整体思路:
* 以行为深搜递进的变量;每次递进时又检索该行的每一列
*
*
* */
public class 受伤的皇后 {
// n皇后变种
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n= sc.nextInt();
int[][] arr = new int[n][n];
dfs(arr,0);
System.out.println(count);
sc.close();
}
static int count = 0;
public static void dfs(int[][] arr,int row) {
if(row==arr.length) {
count++;
return;
}
for(int j = 0;j<arr.length;j++) {
if(check(arr,row,j)) {
arr[row][j] = 1;
dfs(arr,row+1);
arr[row][j] = 0;
}
}
}
public static boolean check(int[][] arr,int row,int col) {
for(int i = 0;i<row;i++) {
if(arr[i][col]==1)return false;
}
//检查左上45
for(int i = row-1,j = col-1,a=0;a<=2&&j>=0&&i>=0;i--,j--) {
//与下面的同理
a++;
if(arr[i][j]==1)return false;
}
//检查右上45
for(int i = row-1,j=col+1,a=0;j<arr.length&&i>=0&&a<=2;i--,j++) {
//第一个条件的意思是它的右上对角线上不能被选过;
//而第二个条件是表示我在行数差比三小的对角内不能等1
//大于等于3的话是可以的,也可以使用计数法来解决,
//计数可以减少循环的次数,如果当count等于3的时候才进行判断对角线
a++;
if(arr[i][j] == 1)return false;
}
return true;
}
}
蓝桥杯模拟赛2021——受伤的皇后
于 2022-03-12 22:00:12 首次发布