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