From 7a429700ae1bc4b5f99f0ee8fd9b510d5f13d9ba Mon Sep 17 00:00:00 2001 From: ckl <1051928078@qq.com> Date: Mon, 17 Oct 2022 20:16:55 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200052.N=E7=9A=87=E5=90=8EII?= =?UTF-8?q?.md=20Java=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0052.N皇后II.md | 49 +++++++++++++++++++++++++++++++++++++- 1 file changed, 48 insertions(+), 1 deletion(-) 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; + } +} +```