mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 00:43:04 +08:00
添加 0052.N皇后II.md C语言解法
This commit is contained in:
@ -143,5 +143,65 @@ var totalNQueens = function(n) {
|
||||
return count;
|
||||
};
|
||||
```
|
||||
|
||||
C
|
||||
```c
|
||||
//path[i]为在i行,path[i]列上存在皇后
|
||||
int *path;
|
||||
int pathTop;
|
||||
int answer;
|
||||
//检查当前level行index列放置皇后是否合法
|
||||
int isValid(int index, int level) {
|
||||
int i;
|
||||
//updater为若斜角存在皇后,其所应在的列
|
||||
//用来检查左上45度是否存在皇后
|
||||
int lCornerUpdater = index - level;
|
||||
//用来检查右上135度是否存在皇后
|
||||
int rCornerUpdater = index + level;
|
||||
for(i = 0; i < pathTop; ++i) {
|
||||
//path[i] == index检查index列是否存在皇后
|
||||
//检查斜角皇后:只要path[i] == updater,就说明当前位置不可放置皇后。
|
||||
//path[i] == lCornerUpdater检查左上角45度是否有皇后
|
||||
//path[i] == rCornerUpdater检查右上角135度是否有皇后
|
||||
if(path[i] == index || path[i] == lCornerUpdater || path[i] == rCornerUpdater)
|
||||
return 0;
|
||||
//更新updater指向下一行对应的位置
|
||||
++lCornerUpdater;
|
||||
--rCornerUpdater;
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
//回溯算法:level为当前皇后行数
|
||||
void backTracking(int n, int level) {
|
||||
//若path中元素个数已经为n,则证明有一种解法。answer+1
|
||||
if(pathTop == n) {
|
||||
++answer;
|
||||
return;
|
||||
}
|
||||
|
||||
int i;
|
||||
for(i = 0; i < n; ++i) {
|
||||
//若当前level行,i列是合法的放置位置。就将i放入path中
|
||||
if(isValid(i, level)) {
|
||||
path[pathTop++] = i;
|
||||
backTracking(n, level + 1);
|
||||
//回溯
|
||||
--pathTop;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
int totalNQueens(int n){
|
||||
answer = 0;
|
||||
pathTop = 0;
|
||||
path = (int *)malloc(sizeof(int) * n);
|
||||
|
||||
backTracking(n, 0);
|
||||
|
||||
return answer;
|
||||
}
|
||||
```
|
||||
|
||||
-----------------------
|
||||
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>
|
||||
|
Reference in New Issue
Block a user