OptaPlanner笔记6 N皇后

news2024/10/7 4:30:58

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.coloradmin.cn/o/870976.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

Python语言基础---选择判断循环结构详解

文章目录 &#x1f340;引言&#x1f340;if语句&#x1f340;if-else语句&#x1f340;if-elif-else语句&#x1f340;for循环&#x1f340;while循环 &#x1f340;引言 在Python编程语言中&#xff0c;选择判断和循环是两个非常重要的概念。它们可以让我们根据条件执行不同的…

分布式应用:Zabbix监控Tomcat

目录 一、理论 1.Zabbix监控Tomcat 二、实验 1.Zabbix监控Tomcat 三、问题 1.获取软件包失败 2.tomcat 配置 JMX remote monitor不生效 3.Zabbix客户端日志报错 一、理论 1.Zabbix监控Tomcat &#xff08;1&#xff09;环境 zabbix服务端&#xff1a;192.168.204.214 …

模型性能的主要指标

主要参数 ROC 曲线和混淆矩阵都是用来评估分类模型性能的工具 ROC曲线&#xff08;Receiver Operating Characteristic curve&#xff09;&#xff1a; ROC曲线描述了当阈值变化时&#xff0c;真正类率&#xff08;True Positive Rate, TPR&#xff09;和假正类率&#xff0…

SAP 收藏夹Favorites介绍,收藏夹导入/导出功能

作为SAP用户&#xff0c;经常需要使用一些事务代码T-Code, 很多时候会因为不常用其中的一些遗忘这个功能&#xff0c;所以这时候分类收藏好不同Module的事务代码到收藏夹里是一个不错的选择。 经常面临的一个场景就是需要变换系统环境&#xff0c;比如从Client A01,去到Client…

springcloud 基础

SprinbCloud微服务简介 架构发展历史 SpringBoot由baiPivotal团队在2013年开始研发、2014年4月发布第一个du版本的全新开源的轻量级框架。 它基zhi于Spring4.0设计&#xff0c;不dao仅继承了Spring框架原有的优秀特性&#xff0c;而且还通过简化配置来进一步简化了Spring应用…

QIIME 2教程. 11元数据Metadata(2023.5)

QIIME 2用户文档. 11元数据 Metadata in QIIME 2 https://docs.qiime2.org/2023.5/tutorials/metadata/ 注&#xff1a;此实例需要一些基础知识&#xff0c;要求完成本系列文章前两篇内容&#xff1a;《1简介和安装Introduction&Install》和4《人体各部位微生物组分析Movin…

【硬件突击 电路】

文章目录 1. 电阻&#xff08;Resistor&#xff09;&#xff1a;2. 电容&#xff08;Capacitor&#xff09;&#xff1a;3. 电感&#xff1a;4、 RC、RL、RLC电路结构及工作原理基尔霍夫定律基尔霍夫电流定律&#xff08;KCL&#xff09;基尔霍夫电压定律&#xff08;KVL&#…

【舌尖优省PLUS】美团、饿了么外卖免费领红包,尽情享受美食与省钱!

家人们&#xff01;我昨天刚开发完并上线了一个超棒的外卖免费领红包的小程序&#xff0c;它叫做【舌尖优省PLUS】&#xff01;如果你喜欢美食&#xff0c;还想省下一些钱&#xff0c;那这个小程序绝对不能错过&#xff01; 在【舌尖优省PLUS】上&#xff0c;你可以通过简单的…

react 生命周期方法

组件的生命周期 每个组件都包含 “生命周期方法”&#xff0c;你可以重写这些方法&#xff0c;以便于在运行过程中特定的阶段执行这些方法。你可以使用此生命周期图谱作为速查表。在下述列表中&#xff0c;常用的生命周期方法会被加粗。其余生命周期函数的使用则相对罕见。 挂…

第4章:决策树

停止 当前分支样本均为同一类时&#xff0c;变成该类的叶子节点。当前分支类型不同&#xff0c;但是已经没有可以用来分裂的属性时&#xff0c;变成类别样本更多的那个类别的叶子节点。当前分支为空时&#xff0c;变成父节点类别最多的类的叶子节点。 ID3 C4.5 Cart 过拟合 缺…

springcloud3 sleuth实现链路状态监控

一 slueth的介绍 1.1 slueth的作用 在微服务框架中&#xff0c;一个由客户端发起的请求在后端系统中会经过多个不同的服务节点调用来协同产生最后的请求结果&#xff0c;每一个阶段请求都会形成一条复杂的分布式调用链路&#xff0c;链路中任何一环出现高延时或者错误都会引起…

通讯协议038——全网独有的OPC HDA知识一之聚合(七)最小值

本文简单介绍OPC HDA规范的基本概念&#xff0c;更多通信资源请登录网信智汇(wangxinzhihui.com)。 本节旨在详细说明HDA聚合的要求和性能。其目的是使HDA聚合标准化&#xff0c;以便HDA客户端能够可靠地预测聚合计算的结果并理解其含义。如果用户需要聚合中的自定义功能&…

MySQL环境安装

文章目录 MySQL环境安装1. 卸载1.1 卸载不要的环境1.2 检查卸载系统安装包 2. 安装2.1 获取mysql官方yum源2.2 安装mysql的yum源2.3 安装mysql服务 3. 登录(1)(2)(3) 4. 配置my.cnf MySQL环境安装 说明&#xff1a; 安装与卸载中&#xff0c;用户全部切换成为root&#xff0c…

基于YOLOv8+PyQt5开发的行人过马路危险行为检测告警系统(附数据集和源码下载)

系列文章目录 文章目录 系列文章目录前言欢迎来到我的博客&#xff01;我很高兴能与大家分享关于基于YOLOv8的行人过马路危险行为检测告警系统的内容。 一、系统特点1. 采用最新最优秀的目标检测算法YOLOv82. 系统分别基于PyQt5开发了两种GUI图形界面&#xff0c;供大家学习使用…

ruoyi-vue-pro yudao 项目bpm模块启用及相关SQL脚本

目前ruoyi-vue-pro 项目虽然开源&#xff0c;但是bpm模块被屏蔽了&#xff0c;查看文档却要收费 199元&#xff08;知识星球&#xff09;&#xff0c;价格有点太高了吧。 分享下如何启用 bpm 模块&#xff0c;顺便贴上sql相关脚本。 一、启用模块 修改根目录 pom.xml 启用模…

Day 29 C++ STL- 函数对象(Function Object)(仿函数)

文章目录 函数对象概念概念本质 函数对象使用特点示例 谓词——返回bool类型的仿函数谓词概念一元谓词——operator()参数只有一个的谓词二元谓词——operator()参数只有俩个的谓词 内建函数对象&#xff08;Builtin Function Objects&#xff09;内建函数对象概念注意算术仿函…

Flowable-边界事件-补偿边界事件

目录 定义图形标记XML内容使用示例演示demo 定义 补偿边界事件可以为所依附的节点附加补偿处理器&#xff0c;通过关联连接到补偿处理器&#xff08;compensation handler&#xff09;。补偿边界事件会在流程活动完成后根据情况&#xff08;事务取消或者补偿中间事件触发&…

WAVE SUMMIT2023六大分会场同步开启,飞桨+文心大模型加速区域产业智能化!

由深度学习技术及应用国家工程研究中心主办、百度飞桨和文心大模型承办的WAVE SUMMIT深度学习开发者大会2023将于8月16日重磅来袭&#xff01;届时上海、广州、深圳、成都、南昌和宁波六大分会场将同步开启&#xff01; 分会汇聚区域产业大咖、科研机构专家、知名学者和技术大牛…

股票量化分析工具QTYX使用攻略——盘口异动实时监测(更新2.6.8)

QTYX简介‍‍‍ 股票量化交易系统QTYX是一个即可以用于学习&#xff0c;也可以用于实战炒股分析的系统。 分享QTYX系统目的是提供给大家一个搭建量化系统的模版&#xff0c;最终帮助大家搭建属于自己的系统。因此我们提供源码&#xff0c;可以根据自己的风格二次开发。 关于QTY…

研究机构:PayPal稳定币PYUSD有望成为「数字资产」的重要用例

作者&#xff1a;Greg Cipolaro&#xff0c;NYDIG 全球研究主管 编译&#xff1a;WEEX 唯客 本文主要探讨两个话题&#xff1a;1. 过去两周&#xff0c;Crypto ETF 的申请数量激增&#xff0c;它们的审核流程是怎样的&#xff1f;2. 金融科技巨头 PayPal 已推出自己的稳定币 PY…