mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 11:34:46 +08:00
添加 0052.N皇后II.md Java版本
This commit is contained in:
@ -256,7 +256,54 @@ int totalNQueens(int n){
|
|||||||
return answer;
|
return answer;
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
Java
|
||||||
|
```java
|
||||||
|
class Solution {
|
||||||
|
int count = 0;
|
||||||
|
public int totalNQueens(int n) {
|
||||||
|
char[][] board = new char[n][n];
|
||||||
|
for (char[] chars : board) {
|
||||||
|
Arrays.fill(chars, '.');
|
||||||
|
}
|
||||||
|
backTrack(n, 0, board);
|
||||||
|
return count;
|
||||||
|
}
|
||||||
|
private void backTrack(int n, int row, char[][] board) {
|
||||||
|
if (row == n) {
|
||||||
|
count++;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
for (int col = 0; col < n; col++) {
|
||||||
|
if (isValid(row, col, n, board)) {
|
||||||
|
board[row][col] = 'Q';
|
||||||
|
backTrack(n, row + 1, board);
|
||||||
|
board[row][col] = '.';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
private boolean isValid(int row, int col, int n, char[][] board) {
|
||||||
|
// 检查列
|
||||||
|
for (int i = 0; i < row; ++i) {
|
||||||
|
if (board[i][col] == 'Q') {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// 检查45度对角线
|
||||||
|
for (int i = row - 1, j = col - 1; i >= 0 && j >= 0; i--, j--) {
|
||||||
|
if (board[i][j] == 'Q') {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// 检查135度对角线
|
||||||
|
for (int i = row - 1, j = col + 1; i >= 0 && j <= n - 1; i--, j++) {
|
||||||
|
if (board[i][j] == 'Q') {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
<p align="center">
|
<p align="center">
|
||||||
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
|
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
|
||||||
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
|
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
|
||||||
|
Reference in New Issue
Block a user