OptaPlanner笔记6 N皇后

N 个皇后

问题描述

将n个皇后放在n大小的棋盘上,没有两个皇后可以互相攻击。 最常见的 n 个皇后谜题是八个皇后谜题,n = 8:
在这里插入图片描述
约束:

  • 使用 n 列和 n 行的棋盘。
  • 在棋盘上放置n个皇后。
  • 没有两个女王可以互相攻击。女王可以攻击同一水平线、垂直线或对角线上的任何其他女王。

求解结果(time limit 5s)

在这里插入图片描述

问题大小

n搜索空间
4256
810^7
1610^19
3210^48
6410^115
25610^616

域模型

@Data
@AllArgsConstructor
public class Column {
    private int index;
}
@Data
@AllArgsConstructor
public class Row {
    private int index;
}
@Data
@AllArgsConstructor
@NoArgsConstructor
@PlanningEntity
public class Queen {
    @PlanningId
    private Integer id;
    @PlanningVariable
    private Column column;
    @PlanningVariable
    private Row row;
    // 升序对角线索引(左上到右下)
    public int getAscendingDiagonalIndex() {
        return column.getIndex() + row.getIndex();
    }
    // 降序对角线索引(左下到右上)
    public int getDescendingDiagonalIndex() {
        return column.getIndex() - row.getIndex();
    }
}
@Data
@AllArgsConstructor
@NoArgsConstructor
@PlanningSolution
public class NQueen {
    @ValueRangeProvider
    @ProblemFactCollectionProperty
    private List<Column> columnList;
    @ValueRangeProvider
    @ProblemFactCollectionProperty
    private List<Row> rowList;
    @PlanningEntityCollectionProperty
    private List<Queen> queenList;
    @PlanningScore
    private HardSoftScore score;
}

例如:
在这里插入图片描述

QueenColumnRowAscendingDiagonalIndexDescendingDiagonalIndex
A1011 (**)-1
B010 (*)1 (**)1
C22240
D030 (*)33

(*)(**)的皇后可以互相攻击

求解器(约束提供者)

public class NQueenConstraintProvider implements ConstraintProvider {
    @Override
    public Constraint[] defineConstraints(ConstraintFactory constraintFactory) {
        return new Constraint[]{
        		// 列冲突
                columnConflict(constraintFactory),
                // 行冲突
                rowConflict(constraintFactory),
                // 升序对角线冲突
                ascendingDiagonalIndexConflict(constraintFactory),
                // 降序对角线冲突
                descendingDiagonalIndexConflict(constraintFactory),
        };
    }

    public Constraint columnConflict(ConstraintFactory constraintFactory) {
        return constraintFactory
                .forEach(Queen.class)
                .join(Queen.class,
                        Joiners.equal(Queen::getColumn),
                        Joiners.lessThan(Queen::getId))
                .penalize(HardSoftScore.ONE_HARD)
                .asConstraint("Column conflict");
    }

    public Constraint rowConflict(ConstraintFactory constraintFactory) {
        return constraintFactory
                .forEach(Queen.class)
                .join(Queen.class,
                        Joiners.equal(Queen::getRow),
                        Joiners.lessThan(Queen::getId))
                .penalize(HardSoftScore.ONE_HARD)
                .asConstraint("Row conflict");
    }

    public Constraint ascendingDiagonalIndexConflict(ConstraintFactory constraintFactory) {
        return constraintFactory
                .forEach(Queen.class)
                .join(Queen.class,
                        Joiners.equal(Queen::getAscendingDiagonalIndex),
                        Joiners.lessThan(Queen::getId))
                .penalize(HardSoftScore.ONE_HARD)
                .asConstraint("AscendingDiagonalIndex conflict");
    }

    public Constraint descendingDiagonalIndexConflict(ConstraintFactory constraintFactory) {
        return constraintFactory
                .forEach(Queen.class)
                .join(Queen.class,
                        Joiners.equal(Queen::getDescendingDiagonalIndex),
                        Joiners.lessThan(Queen::getId))
                .penalize(HardSoftScore.ONE_HARD)
                .asConstraint("DescendingDiagonalIndex conflict");
    }
}

应用

public class NQueenApp {
    public static void main(String[] args) {
        SolverFactory<NQueen> solverFactory = SolverFactory.create(new SolverConfig()
                .withSolutionClass(NQueen.class)
                .withEntityClasses(Queen.class)
                .withConstraintProviderClass(NQueenConstraintProvider.class)
                .withTerminationSpentLimit(Duration.ofSeconds(5)));
        NQueen problem = generateDemoData();
        Solver<NQueen> solver = solverFactory.buildSolver();
        NQueen solution = solver.solve(problem);
        printTimetable(solution);
    }

    public static NQueen generateDemoData() {
        List<Column> columnList = new ArrayList<>();
        List<Row> rowList = new ArrayList<>();
        List<Queen> queenList = new ArrayList<>();
        for (int i = 0; i < 8; i++) {
            columnList.add(new Column(i));
            rowList.add(new Row(i));
            queenList.add(new Queen(i, null, null));
        }
        return new NQueen(columnList, rowList, queenList, null);
    }

    private static void printTimetable(NQueen nQueen) {
        System.out.println("");
        List<Column> columnList = nQueen.getColumnList();
        List<Row> rowList = nQueen.getRowList();
        List<Queen> queenList = nQueen.getQueenList();
        Map<Column, Map<Row, List<Queen>>> queenMap = queenList.stream()
                .filter(queen -> queen.getColumn() != null && queen.getRow() != null)
                .collect(Collectors.groupingBy(Queen::getColumn, Collectors.groupingBy(Queen::getRow)));
        System.out.println("|     | " + columnList.stream()
                .map(room -> String.format("%-3s", room.getIndex())).collect(Collectors.joining(" | ")) + " |");
        System.out.println("|" + "-----|".repeat(columnList.size() + 1));
        for (Column column : columnList) {
            List<List<Queen>> cellList = rowList.stream()
                    .map(row -> {
                        Map<Row, List<Queen>> byRowMap = queenMap.get(column);
                        if (byRowMap == null) {
                            return Collections.<Queen>emptyList();
                        }
                        List<Queen> cellQueenList = byRowMap.get(row);
                        if (cellQueenList == null) {
                            return Collections.<Queen>emptyList();
                        }
                        return cellQueenList;
                    })
                    .collect(Collectors.toList());

            System.out.println("| " + String.format("%-3s", column.getIndex()) + " | "
                    + cellList.stream().map(cellQueenList -> String.format("%-3s",
                            cellQueenList.stream().map(queen -> queen.getId().toString()).collect(Collectors.joining(", "))))
                    .collect(Collectors.joining(" | "))
                    + " |");
            System.out.println("|" + "-----|".repeat(columnList.size() + 1));
        }
        List<Queen> unassignedQueens = queenList.stream()
                .filter(Queen -> Queen.getColumn() == null || Queen.getRow() == null)
                .collect(Collectors.toList());
        if (!unassignedQueens.isEmpty()) {
            System.out.println("");
            System.out.println("Unassigned Queens");
            for (Queen Queen : unassignedQueens) {
                System.out.println("  " + Queen.getColumn() + " - " + Queen.getRow());
            }
        }
    }
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/73186.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

YOLO v8目标跟踪详细解读(二)

上一篇&#xff0c;结合代码&#xff0c;我们详细的介绍了YOLOV8目标跟踪的Pipeline。大家应该对跟踪的流程有了大致的了解&#xff0c;下面我们将对跟踪中出现的卡尔曼滤波进行解读。 1.卡尔曼滤波器介绍 卡尔曼滤波&#xff08;kalman Filtering&#xff09;是一种利用线性…

Java多款线程池,总有一款适合你。

线程池的选择 一&#xff1a;故事背景二&#xff1a;线程池原理2.1 ThreadPoolExecutor的构造方法的七个参数2.1.1 必须参数2.1.2 可选参数 2.2 ThreadPoolExecutor的策略2.3 线程池主要任务处理流程2.4 ThreadPoolExecutor 如何做到线程复用 三&#xff1a;四种常见线程池3.1 …

Jenkins+Docker+SpringCloud微服务持续集成项目优化和微服务集群

JenkinsDockerSpringCloud微服务持续集成项目优化和微服务集群 JenkinsDockerSpringCloud部署方案优化JenkinsDockerSpringCloud集群部署流程说明修改所有微服务配置 设计Jenkins集群项目的构建参数编写多选项遍历脚本多项目提交进行代码审查多个项目打包及构建上传镜像把Eurek…

Vue 引入 Element-UI 组件库

Element-UI 官网地址&#xff1a;https://element.eleme.cn/#/zh-CN 完整引入&#xff1a;会将全部组件打包到项目中&#xff0c;导致项目过大&#xff0c;首次加载时间过长。 下载 Element-UI 一、打开项目&#xff0c;安装 Element-UI 组件库。 使用命令&#xff1a; npm …

时序预测 | MATLAB实现基于LSTM长短期记忆神经网络的时间序列预测-递归预测未来(多指标评价)

时序预测 | MATLAB实现基于LSTM长短期记忆神经网络的时间序列预测-递归预测未来(多指标评价) 目录 时序预测 | MATLAB实现基于LSTM长短期记忆神经网络的时间序列预测-递归预测未来(多指标评价)预测结果基本介绍程序设计参考资料 预测结果 基本介绍 Matlab实现LSTM长短期记忆神经…

[保研/考研机试] KY87 鸡兔同笼 北京大学复试上机题 C++实现

描述 一个笼子里面关了鸡和兔子&#xff08;鸡有2只脚&#xff0c;兔子有4只脚&#xff0c;没有例外&#xff09;。已经知道了笼子里面脚的总数a&#xff0c;问笼子里面至少有多少只动物&#xff0c;至多有多少只动物。 输入描述&#xff1a; 每组测试数据占1行&#xff0c;…

二次封装element-plus上传组件,提供校验、回显等功能

二次封装element-plus上传组件 0 相关介绍1 效果展示2 组件主体3 视频组件4 Demo 0 相关介绍 基于element-plus框架&#xff0c;视频播放器使用西瓜视频播放器组件 相关能力 提供图片、音频、视频的预览功能提供是否为空、文件类型、文件大小、文件数量、图片宽高校验提供图片…

盛元广通食品药品检验检测实验室LIMS系统

随着食品与制药行业法规标准的日益提高和国家两化融合的不断推进&#xff0c;为保障检验工作的客观、公正及科学性&#xff0c;确保制药企业对于生产、实验室、物流、管理的信息化和智能化需求越来越明确&#xff0c;为确保新品可及时得到科学准确的检测检验结果&#xff0c;盛…

H5 和小程序的区别

什么是小程序&#xff1f; 从“微信之父” 张小龙的定义里&#xff0c;我们可以了解到&#xff0c;小程序其实就是内嵌在微信&#xff0c;不需要安装和卸载的一种新应用形态。它具备的两个强属性&#xff1a;提高效率&#xff0c;用完即走&#xff01;因此小程序的设计以轻便、…

微服务02-docker

1、Docker架构 1.1 镜像和容器 Docker中有几个重要的概念: 镜像(Image):Docker将应用程序及其所需的依赖、函数库、环境、配置等文件打包在一起,称为镜像。Docker镜像是用于创建 Docker 容器的模板 。就像面向对象编程中的类。 容器(Container):镜像中的应用程序运…

02:STM32--EXTI外部中断

目录 一:中断 1:简历 2:AFIO 3:EXTI ​编辑 4:NVIC基本结构 5:使用步骤 二:中断的应用 A:对外式红外传感计数器 1:连接图​编辑 2:函数介绍 3:硬件介绍 4:计数代码 B;旋转编码计数器 1:连接图 2:硬件介绍 3:旋转编码器代码: 一:中断 1:简历 中断&#xff1a;在主程…

OpenCV基本操作——图像的基础操作

目录 图像的IO操作读取图像显示图像保存图像 绘制几何图形绘制直线绘制圆形绘制矩形向图像中添加文字效果展示 获取并修改图像中的像素点获取图像的属性图像通道的拆分与合并色彩空间的改变 图像的IO操作 读取图像 cv2.imread()import numpy as np import cv2 imgcv2.imread(…

【Java从0到1学习】08 String类

1. 概述 字符串是由多个字符组成的一串数据(字符序列)&#xff0c;字符串可以看成是字符数组。 在实际开发中&#xff0c;字符串的操作是最常见的操作&#xff0c;没有之一。而Java没有内置的字符串类型&#xff0c;所以&#xff0c;就在Java类库中提供了一个类String 供我们…

Python爬虫:单线程、多线程、多进程

前言 在使用爬虫爬取数据的时候&#xff0c;当需要爬取的数据量比较大&#xff0c;且急需很快获取到数据的时候&#xff0c;可以考虑将单线程的爬虫写成多线程的爬虫。下面来学习一些它的基础知识和代码编写方法。 一、进程和线程 进程可以理解为是正在运行的程序的实例。进…

jvs-rules API数据源配置说明(含配置APIdemo视频)

在JVS中&#xff0c;多数据源支持多种形态的数据接入&#xff0c;其中API是企业生产过程中常见的数据形态。使用数据源的集成配置&#xff0c;以统一的方式管理和集成多个API的数据。这些平台通常提供各种数据转换和处理功能&#xff0c;使得从不同数据源获取和处理数据变得更加…

搭建一个能与大家分享的旅游相册网站——“cpolar内网穿透”

如何用piwigo与cpolar结合共同搭建一个能分享的旅行相册网站 文章目录 如何用piwigo与cpolar结合共同搭建一个能分享的旅行相册网站前言1. 使用piwigo这款开源的图片管理软件2. 需要将piwigi网页复制到phpstudy3. “开始安装”进入自动安装程序4. 创建新相册5. 创建一条空白数据…

Spring Gateway+Security+OAuth2+RBAC 实现SSO统一认证平台

背景&#xff1a;新项目准备用SSO来整合之前多个项目的登录和权限&#xff0c;同时引入网关来做后续的服务限流之类的操作&#xff0c;所以搭建了下面这个系统雏形。 关键词&#xff1a;Spring Gateway, Spring Security, JWT, OAuth2, Nacos, Redis, Danymic datasource, Jav…

ansible剧本之role角色模块

role角色 一&#xff1a;Roles 模块1.roles 的目录结构&#xff1a;2.roles 内各目录含义解释3.在一个 playbook 中使用 roles 的步骤&#xff1a;&#xff08;1&#xff09;创建以 roles 命名的目录&#xff08;2&#xff09;创建全局变量目录&#xff08;可选&#xff09;&am…

Java进阶-Oracle(二十一)(2)

&#x1f33b;&#x1f33b; 目录 一、Oracle 数据库的操作(DDL DML DQL DCL TPL)1.1 标识符、关键字、函数等1.1.1 数值类型&#xff1a;1.1.2 字符串类型&#xff1a;1.1.3 日期类型1.1.4 大的数据类型--适合保存更多的数据 1.2 运算符1.3 函数---预定义函数、自定义函数&…

户外组网摆脱布线困扰,工业5G网关实现无人值守、远程实时监控

在物联网通信技术发达的2023&#xff0c;网络覆盖对所及之处的全面覆盖&#xff0c;科技发展的促使下很多高危户外场景也在思考如何利用无线技术提高人员安全及现场无人化管理。 煤矿是我们国家不可缺少的重要能源&#xff0c;其开采过程的危险系数也是众所皆知的&#xff0c;…