From 00f2aa679318c12921ce974168ad3b7728bc0ac5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=93=88=E5=93=88=E5=93=88?= <76643786+Projecthappy@users.noreply.github.com> Date: Wed, 16 Aug 2023 15:28:28 +0800 Subject: [PATCH] =?UTF-8?q?0051.N=E7=9A=87=E5=90=8E=EF=BC=8Cjava=E6=B7=BB?= =?UTF-8?q?=E5=8A=A0=E6=96=B0=E6=96=B9=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0051.N皇后.md | 52 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) diff --git a/problems/0051.N皇后.md b/problems/0051.N皇后.md index 6bc4fa78..71c40238 100644 --- a/problems/0051.N皇后.md +++ b/problems/0051.N皇后.md @@ -345,6 +345,58 @@ class Solution { } } ``` +```java +//该方法主要特点在于用一个一维数组暂存皇后的位置,数组下标代表行,数组下标的值代表列,并初始化一个长度为n-1,值全为'.'的模板字符串 +//在找到合法方案时,遍历数组,在模板字符串下标为数组值的位置插入Q +class Solution { + //结果 + List> result = new ArrayList<>(); + //储存皇后的位置,下标为行,值为列 + int[] queenIndex; + //棋盘中一行的字符串模板 + String template; + int size; + + public List> solveNQueens(int n) { + size = n; + template = ".".repeat(n - 1); + queenIndex = new int[n]; + deal(0); + return result; + } + + void deal(int index) { + //遍历当前行的所有位置(尝试在这行每个位置放置皇后) + for (int i = 0; i < size; i++) { + queenIndex[index] = i; + //检查在当前位置放置皇后是否合法 + if (check(index, i)) { + //如果当前的行是最后一行,就说明当前皇后的摆放已经是完整并且合法的,在结果集中加入当前的摆放方案 + if (index == size - 1) { + List tmp = new ArrayList<>(size); + //遍历当前的皇后位置,在模板字符串对应的位置加入Q,再加入到结果集中 + for (Integer integer : queenIndex) { + tmp.add(new StringBuilder(template).insert(integer, "Q").toString()); + } + result.add(tmp); + return; + } + //如果当前不是最后一行,还需要进入下一行 + deal(index + 1); + } + } + } + + boolean check(int rowIndex, int columnIndex) { + for (int i = 0; i < rowIndex; i++) { + if (queenIndex[i] == columnIndex || (Math.abs(queenIndex[i] - columnIndex) == Math.abs(i - rowIndex))) { + return false; + } + } + return true; + } +} +``` ### Python