当前位置: 首页 > news >正文

代码随想录算法训练营第三十天|51. N皇后

|51. N皇后

public List<List<String>> solveNQueens(int n) {List<List<String>> res = new ArrayList<>();return null;}void backtracking1(int n, int row, int[] columns) {// 是否在所有n行里都摆放好了皇后?if (row == n) {count++;// 找到了新的摆放方法return;}// 尝试着将皇后放置在当前行中的每一列for (int col = 0; col < n; col++) {columns[row] = col;// 检查是否合法,如果合法就继续到下一行if (check(row, col, columns)) {backtracking1(n, row + 1, columns);}
// 如果不合法,就不要把皇后放在这列中 (回溯)columns[row] = -1;}}boolean check1(int row, int col, int[] columns) {for (int r = 0; r < row; r++) {if (columns[r] == col ||row - r == Math.abs(columns[r] - col)) {return false;}}return true;}public List<List<String>> solveNQueens(int n) {int[] queueMax = new int[n];List<List<String>> lists = new ArrayList<>();check(0, n, queueMax, lists);return lists;}public void check(int n, int max, int[] queueMax, List<List<String>> lists) {if (n == max) {print(queueMax, lists);return;}for (int i = 0; i < max; i++) {queueMax[n] = i;if (judge(n, queueMax)) {check(n + 1, max, queueMax, lists);}}}public void print(int[] queueMax, List<List<String>> lists) {List<String> stringList = new ArrayList<>();for (int i = 0; i < queueMax.length; i++) {String res = "";for (int j = 0; j < queueMax.length; j++) {if (j == queueMax[i]) {res = res.concat("Q");} else {res = res.concat(".");}}stringList.add(res);}lists.add(stringList);}public boolean judge(int n, int[] queueMax) {for (int i = 0; i < n; i++) {if (queueMax[i] == queueMax[n] || Math.abs(n - i) == Math.abs(queueMax[n] - queueMax[i])) {return false;}}return true;}
http://www.lryc.cn/news/287314.html

相关文章:

  • Kubernetes(K8S)各种攻击方法
  • 【MySQL】内外连接
  • selenium执行出现异常,SessionNotCreatedException ChromeDriver only supports
  • Flink:快速掌握批处理数据源的创建方法
  • 基于cubeMX的正点原子miniSTM32对W25Q64的存储使用
  • C++笔记(三)
  • c语言不定参数
  • 云手机与实体手机的对比
  • diffusion 和 gan 的优缺点对比
  • VC++中使用OpenCV进行人脸检测
  • 11Docker数据持久化
  • RK3588平台开发系列讲解(视频篇)RKMedia框架
  • Vue3 Teleport 将组件传送到外层DOM位置
  • 【学网攻】 第(5)节 -- Cisco VTP的使用
  • uniapp复选框 实现排他选项
  • openssl3.2/test/certs - 004 - cross root and root cross cert
  • 图像分类】【深度学习】【轻量级网络】【Pytorch版本】EfficientNet_V2模型算法详解
  • 05.Elasticsearch应用(五)
  • npm更换镜像
  • 野指针(C语言)
  • 动物姿态识别(数据集+代码)
  • JSON-handle工具安装及使用
  • kali安装LAMP和DVWA
  • 上门服务小程序|预约上门服务系统开发有哪些功能?
  • uniapp vue3版本引用 jsencrypt加密库报错:“default“ is not exported by……
  • 【WPF.NET开发】WPF中的双向功能
  • Pytest 测试框架与Allure 测试报告——Allure2测试报告-L3
  • 【机器学习300问】16、逻辑回归模型实现分类的原理?
  • OPC【4】:物理包
  • 关于 Go 协同程序(Coroutines 协程)、Go 汇编及一些注意事项。