From a490c4b4fd7d3a2d22dfe2e20bb27dc55cd9d237 Mon Sep 17 00:00:00 2001 From: GitNaruto <19946254539@163.com> Date: Fri, 25 Nov 2022 15:00:03 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A00051N=E7=9A=87=E5=90=8EJava?= =?UTF-8?q?=E7=89=88=E6=9C=AC(=E6=96=B9=E6=B3=952)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0051.N皇后.md | 50 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) diff --git a/problems/0051.N皇后.md b/problems/0051.N皇后.md index 83d0cd94..16fdf347 100644 --- a/problems/0051.N皇后.md +++ b/problems/0051.N皇后.md @@ -291,6 +291,56 @@ class Solution { } ``` +```java +// 方法2:使用boolean数组表示已经占用的直(斜)线 +class Solution { + List> res = new ArrayList<>(); + boolean[] usedCol, usedDiag45, usedDiag135; // boolean数组中的每个元素代表一条直(斜)线 + public List> solveNQueens(int n) { + usedCol = new boolean[n]; // 列方向的直线条数为 n + usedDiag45 = new boolean[2 * n - 1]; // 45°方向的斜线条数为 2 * n - 1 + usedDiag135 = new boolean[2 * n - 1]; // 135°方向的斜线条数为 2 * n - 1 + //用于收集结果, 元素的index表示棋盘的row,元素的value代表棋盘的column + int[] board = new int[n]; + backTracking(board, n, 0); + return res; + } + private void backTracking(int[] board, int n, int row) { + if (row == n) { + //收集结果 + List temp = new ArrayList<>(); + for (int i : board) { + char[] str = new char[n]; + Arrays.fill(str, '.'); + str[i] = 'Q'; + temp.add(new String(str)); + } + res.add(temp); + return; + } + + for (int col = 0; col < n; col++) { + if (usedCol[col] | usedDiag45[row + col] | usedDiag135[row - col + n - 1]) { + continue; + } + board[row] = col; + // 标记该列出现过 + usedCol[col] = true; + // 同一45°斜线上元素的row + col为定值, 且各不相同 + usedDiag45[row + col] = true; + // 同一135°斜线上元素row - col为定值, 且各不相同 + // row - col 值有正有负, 加 n - 1 是为了对齐零点 + usedDiag135[row - col + n - 1] = true; + // 递归 + backTracking(board, n, row + 1); + usedCol[col] = false; + usedDiag45[row + col] = false; + usedDiag135[row - col + n - 1] = false; + } + } +} +``` + ### Python ```python