Update 0051.N皇后.md

This commit is contained in:
哈哈哈
2023-08-29 11:12:04 +08:00
committed by GitHub
parent 00f2aa6793
commit 99eb035fee

View File

@ -345,58 +345,6 @@ class Solution {
}
}
```
```java
//该方法主要特点在于用一个一维数组暂存皇后的位置数组下标代表行数组下标的值代表列并初始化一个长度为n-1值全为'.'的模板字符串
//在找到合法方案时遍历数组在模板字符串下标为数组值的位置插入Q
class Solution {
//结果
List<List<String>> result = new ArrayList<>();
//储存皇后的位置,下标为行,值为列
int[] queenIndex;
//棋盘中一行的字符串模板
String template;
int size;
public List<List<String>> 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<String> 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