添加(0052.N皇后II.md):增加typescript版本

This commit is contained in:
Steve2020
2022-06-12 12:17:26 +08:00
parent a6ce79a98a
commit dd20ca032f

View File

@ -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
```c ```c
//path[i]为在i行path[i]列上存在皇后 //path[i]为在i行path[i]列上存在皇后
int *path; int *path;