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

[pull] master from youngyangyang04:master #340

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
pull merged 9 commits into AlgorithmAndLeetCode:master from youngyangyang04:master
Sep 3, 2023
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
0051.N皇后,java添加新方法
  • Loading branch information
sdd-bob authored Aug 16, 2023
commit 00f2aa679318c12921ce974168ad3b7728bc0ac5
52 changes: 52 additions & 0 deletions problems/0051.N皇后.md
View file Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -345,6 +345,58 @@ 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

Expand Down

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