Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 00f2aa6

Browse files
authored
0051.N皇后,java添加新方法
1 parent 77f448e commit 00f2aa6

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

‎problems/0051.N皇后.md‎

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -345,6 +345,58 @@ class Solution {
345345
}
346346
}
347347
```
348+
```java
349+
//该方法主要特点在于用一个一维数组暂存皇后的位置,数组下标代表行,数组下标的值代表列,并初始化一个长度为n-1,值全为'.'的模板字符串
350+
//在找到合法方案时,遍历数组,在模板字符串下标为数组值的位置插入Q
351+
class Solution {
352+
//结果
353+
List<List<String>> result = new ArrayList<>();
354+
//储存皇后的位置,下标为行,值为列
355+
int[] queenIndex;
356+
//棋盘中一行的字符串模板
357+
String template;
358+
int size;
359+
360+
public List<List<String>> solveNQueens(int n) {
361+
size = n;
362+
template = ".".repeat(n - 1);
363+
queenIndex = new int[n];
364+
deal(0);
365+
return result;
366+
}
367+
368+
void deal(int index) {
369+
//遍历当前行的所有位置(尝试在这行每个位置放置皇后)
370+
for (int i = 0; i < size; i++) {
371+
queenIndex[index] = i;
372+
//检查在当前位置放置皇后是否合法
373+
if (check(index, i)) {
374+
//如果当前的行是最后一行,就说明当前皇后的摆放已经是完整并且合法的,在结果集中加入当前的摆放方案
375+
if (index == size - 1) {
376+
List<String> tmp = new ArrayList<>(size);
377+
//遍历当前的皇后位置,在模板字符串对应的位置加入Q,再加入到结果集中
378+
for (Integer integer : queenIndex) {
379+
tmp.add(new StringBuilder(template).insert(integer, "Q").toString());
380+
}
381+
result.add(tmp);
382+
return;
383+
}
384+
//如果当前不是最后一行,还需要进入下一行
385+
deal(index + 1);
386+
}
387+
}
388+
}
389+
390+
boolean check(int rowIndex, int columnIndex) {
391+
for (int i = 0; i < rowIndex; i++) {
392+
if (queenIndex[i] == columnIndex || (Math.abs(queenIndex[i] - columnIndex) == Math.abs(i - rowIndex))) {
393+
return false;
394+
}
395+
}
396+
return true;
397+
}
398+
}
399+
```
348400

349401
### Python
350402

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /