diff --git a/problems/0052.N皇后II.md b/problems/0052.N皇后II.md index f1edd281..e4faac0c 100644 --- a/problems/0052.N皇后II.md +++ b/problems/0052.N皇后II.md @@ -256,7 +256,54 @@ int totalNQueens(int n){ 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; + } +} +```