From dd20ca032fab47e0e05f9d32c05f528872dcf83a Mon Sep 17 00:00:00 2001 From: Steve2020 <841532108@qq.com> Date: Sun, 12 Jun 2022 12:17:26 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880052.N=E7=9A=87?= =?UTF-8?q?=E5=90=8EII.md=EF=BC=89=EF=BC=9A=E5=A2=9E=E5=8A=A0typescript?= =?UTF-8?q?=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 | 54 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) diff --git a/problems/0052.N皇后II.md b/problems/0052.N皇后II.md index 67e439ca..608aeda1 100644 --- a/problems/0052.N皇后II.md +++ b/problems/0052.N皇后II.md @@ -144,7 +144,61 @@ var totalNQueens = function(n) { }; ``` +TypeScript: + +```typescript +// 0-该格为空,1-该格有皇后 +type GridStatus = 0 | 1; +function totalNQueens(n: number): number { + let resCount: number = 0; + const chess: GridStatus[][] = new Array(n).fill(0) + .map(_ => new Array(n).fill(0)); + backTracking(chess, n, 0); + return resCount; + function backTracking(chess: GridStatus[][], n: number, startRowIndex: number): void { + if (startRowIndex === n) { + resCount++; + return; + } + for (let j = 0; j < n; j++) { + if (checkValid(chess, startRowIndex, j, n) === true) { + chess[startRowIndex][j] = 1; + backTracking(chess, n, startRowIndex + 1); + chess[startRowIndex][j] = 0; + } + } + } +}; +function checkValid(chess: GridStatus[][], i: number, j: number, n: number): boolean { + // 向上纵向检查 + let tempI: number = i - 1, + tempJ: number = j; + while (tempI >= 0) { + if (chess[tempI][tempJ] === 1) return false; + tempI--; + } + // 斜向左上检查 + tempI = i - 1; + tempJ = j - 1; + while (tempI >= 0 && tempJ >= 0) { + if (chess[tempI][tempJ] === 1) return false; + tempI--; + tempJ--; + } + // 斜向右上检查 + tempI = i - 1; + tempJ = j + 1; + while (tempI >= 0 && tempJ < n) { + if (chess[tempI][tempJ] === 1) return false; + tempI--; + tempJ++; + } + return true; +} +``` + C + ```c //path[i]为在i行,path[i]列上存在皇后 int *path;