蓝桥杯 - 受伤的皇后

解题思路:

递归 + 回溯(n皇后问题的变种)

在 N 皇后问题的解决方案中,我们是从棋盘的顶部向底部逐行放置皇后的,这意味着在任何给定时间,所有未来的行(即当前行之下的所有行)都还没有被探查或放置任何皇后。因此,检查下方行是没有意义的,因为它们总是空的。所以只需要检查左上45°和右上45°。

java 复制代码
import java.util.Scanner;

public class Main {
    static int count = 0;

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int n = scan.nextInt();
        int[][] arr = new int[n][n];
        dfs(arr, 0);
        System.out.println(count);
    }

    public static void dfs(int[][] arr, int row) {
        if (row == arr.length) {
            count++;
            return;
        }
        // 遍历列,因为n行n列,所以arr.length和arr[0].length是一样的
        for (int j = 0; j < arr.length; j++) {
            if (checkValid(arr, row, j)) {
                arr[row][j] = 1;
                dfs(arr, row + 1);
                // 回溯
                arr[row][j] = 0;
            }
        }
    }

    public static boolean checkValid(int[][] arr, int row, int col) {
        // 检查列,因为n行n列,所以row既是行的长度又是列的长度
        for (int i = 0; i < row; i++) {
            if (arr[i][col] == 1) {
                return false;
            }
        }
        // 检查左上45°
        for (int i = row - 1, j = col - 1; i >= 0 && j >= 0; i--, j--) {
            if (arr[i][j] == 1 && Math.abs(row - i) < 3) {
                return false;
            }
        }
        // 检查右上45°
        for (int i = row - 1, j = col + 1; i >= 0 && j < arr.length; i--, j++) {
            if (arr[i][j] == 1 && Math.abs(row - i) < 3) {
                return false;
            }
        }
        return true;
    }
}
相关推荐
蓝色汪洋11 分钟前
xtu oj矩阵
算法
超级大只老咪6 小时前
数组相邻元素比较的循环条件(Java竞赛考点)
java
hh随便起个名6 小时前
力扣二叉树的三种遍历
javascript·数据结构·算法·leetcode
小浣熊熊熊熊熊熊熊丶6 小时前
《Effective Java》第25条:限制源文件为单个顶级类
java·开发语言·effective java
毕设源码-钟学长7 小时前
【开题答辩全过程】以 公交管理系统为例,包含答辩的问题和答案
java·eclipse
啃火龙果的兔子7 小时前
JDK 安装配置
java·开发语言
星哥说事7 小时前
应用程序监控:Java 与 Web 应用的实践
java·开发语言
派大鑫wink7 小时前
【JAVA学习日志】SpringBoot 参数配置:从基础到实战,解锁灵活配置新姿势
java·spring boot·后端
xUxIAOrUIII7 小时前
【Spring Boot】控制器Controller方法
java·spring boot·后端
Dolphin_Home7 小时前
从理论到实战:图结构在仓库关联业务中的落地(小白→中级,附完整代码)
java·spring boot·后端·spring cloud·database·广度优先·图搜索算法