八皇后

八皇后问题是一个以国际象棋为背景的问题:如何能够在 8×8 的国际象棋棋盘上放置八个皇后,使得任何一个皇后都无法直接吃掉其他的皇后?为了达到此目的,任两个皇后都不能处于同一条横行、纵行或斜线上。

//八皇后-回溯法递归实现(学长提供的思路)
#include <cstdio>
using namespace std;

int q[8] = {};

void printQ(){
    static int cnt = 1;
    printf("%d:", cnt);
    ++cnt;
    for(int i = 0; i < 8; i++){
        printf(" %d", q[i]);
    }
    printf("\n");
}
int check(int row, int col){
    q[row] = col;
    for(int i = 0; i < row; i++)
        if(q[i] - q[row] == i - row ||
           q[i] - q[row] == row - i)
           return 0;
    return 1;
}
void queen8(int row){
    if(row == 8){
        printQ();
        return ;
    }
    static int book[8] = {};
    for(int j = 0; j < 8; j++)
        if(book[j] == 0 && check(row, j)){
            book[j] = 1;
            queen8(row + 1);
            book[j] = 0;
        }
}

int main(){
    queen8(0);
    return 0;
}
//八皇后-回溯法迭代实现(强哥写的)
#include <stdio.h>
int q[8] = {0};
int check(int count){
    int i;
    for(i=0; i<count; i++)
        if(q[i]==q[count] || q[i]-q[count]==i-count
           || q[i]-q[count]==count-i) return 0;
    return 1;
}
void printQ(){
    static int count=1;
    printf("%d : ",count);
    int i;
    for(i=0; i<8; i++) printf("%d,",q[i]);
    putchar('\n');
//    getchar();
    count++;
}
void queen8i(){
    int count = 0;
    q[0] = -1;
    while(count>=0){
        q[count]++;
        if(q[count]==8){
            count--;
            continue;
        }
        if(check(count)){
            if(count<7){
                count++;
                q[count] = -1;
            }else{
                printQ();
                count--;
            }

        }
    }
}
void main(){
    queen8i();
}
//八皇后-回溯法迭代实现(自己写的)
#include <stdio.h>
int q[8] = {0};
int check(int count){
    int i;
    for(i=0; i<count; i++)
        if(q[i]==q[count] || q[i]-q[count]==i-count
           || q[i]-q[count]==count-i) return 0;
    return 1;
}
void printQ(){
    static int count=1;
    printf("%d : ",count);
    int i;
    for(i=0; i<8; i++) printf("%d,",q[i]);
    putchar('\n');
//    getchar();
    count++;
}
void queen8i()
{
    int count=0;
    q[0]=-1;
    while(count>=0)
    {
        if(q[count]<7)
            q[count]++;
        else
        {
            count--;
           continue;
        }
        if(check(count))
        {

            if(count==7)
                printQ();
            else{
                count++;
                q[count]=-1;
            }
        }
    }

}
void main(){
    queen8i();
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值