八皇后

八皇后學習

#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);
        }
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章