mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 11:34:46 +08:00
添加(0052.N皇后II.md):增加typescript版本
This commit is contained in:
@ -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;
|
||||
|
Reference in New Issue
Block a user