c基础编程:八皇后问题(递归算法)

#include <stdio.h>
#include <cstdlib>

int eight_array[8] = {0};
int count = 0;

void printf_image(){
    printf("\n 第 %d 种方案 \n",++count);
    for(int i = 0; i < 8; ++i) {
        int j;
        for(j = 0; j < eight_array[i]; ++j) {
            printf("%d ", 0);
        }
        printf("%d ", 1);
        for(int k = ++j; k < 8; ++k){
            printf("%d ", 0);
        }
        printf("\n");
    }
    printf("\n\n");
}

bool enable_place(int row) {
    for(int k = 0; k < row; ++k) {
        if(eight_array[k] == eight_array[row] || (row - k)*(row -k) == (eight_array[row] - eight_array[k])*(eight_array[row] - eight_array[k])){
            return false;
        }
    }
    return true;
}

void eight(int row) {
    if(row > 7){
        printf_image();
    }else {
        for(int i = 0; i < 8; ++i) {
            eight_array[row] = i;
            if(enable_place(row)){
                eight(row+1);
            }
        }
    }

}

int main() {
    eight(0);
    system("pause");
    return 0;
}
posted @ 2012-04-26 13:32  ITMelody  阅读(330)  评论(0编辑  收藏  举报