八皇后學習
#include <stdio.h>
#include <stdlib.h>
#define N 8 // N皇后static int c[N]; // 存放皇后所在棋盤位置 下標表示列 存放的值表示行
static int count = 0; //記錄有多少種擺放的方法
int isTrue(int row); //判斷當前棋子是否合適,合適則繼續深搜,放下一個棋子
void eightQueen(int row);
int main() {
eightQueen(0);
printf("%d", count);
return 0;
}
int isTrue(int row) {
int j;
for( j=0;j!=row;j++){//行相同||對角方向
if(c[row]==c[j] || row-c[row]==j-c[j] || row+c[row]==j+c[j])
return 0;
}
return 1;
}
void eightQueen(int row) {
if(row == N) //判定是否所有棋子擺放完畢
count++;
else {
int col;
for(col = 0; col < N; col++) {
c[row]=col; //擺放棋子
if(isTrue(row)) //判定是否合適,不合適則for循環在下一行進行擺放
eightQueen(row+1);
}
}
}