n皇后问题递归算法(回溯法)

/*n皇后问题递归算法*/

#include <cstdio>
#include <cstdlib>
#include <cstring>
using namespace std;

#define QUEEN 8 //皇后个数
#define MAXR (QUEEN+2)  //棋盘大小

char chess[MAXR][MAXR];    //定义一个棋盘
int count = 0;  //总摆放方法

//初始化棋盘
void init(){
    memset(chess,'0',sizeof(chess));
    for(int i=0; i<MAXR; i++){
        chess[i][0] = chess[i][MAXR-1] = chess[0][i] = chess[MAXR-1][i] = '$';
    }
}

//输出棋盘
void print(){
    count++;
    for(int i=0; i<MAXR; i++){
        for(int j=0; j<MAXR; j++){
            if(!j) printf("%c",chess[i][j]);
            else printf(" %c",chess[i][j]);
        }
        printf("\n");
    }
    printf("\n");
}

//判断布局是否合法
int judge(int x, int y){
    int num = 0;
    for(int i=1; i<MAXR-1; i++){
        if(chess[i][y]=='1') num++;
    }
    for(int i=1; i<MAXR; i++){
        if((x+i< MAXR) && (y+i<MAXR)  && chess[x+i][y+i]=='1') num++;
        if((x+i< MAXR) && (y-i>0)  && chess[x+i][y-i]=='1') num++;
        if((x-i>0) && (y-i>0) && chess[x-i][y-i]=='1') num++;
        if((x-i>0) && (y+i<MAXR)  && chess[x-i][y+i]=='1') num++;
    }
    if(num==1) return 1;
    else return 0;
}

/*n皇后问题递归算法
 *进入本函数时,在n*n棋盘前i-1行已经放置了互不攻击的i-1个棋子。
 *现在从第i行起继续为后续棋子选择合适位置。
*/
void Trial(int i, int n){
    if(i>n) print();    //当i>n时,求得一个合法布局,输出。
    else{
        for(int j=1; j<=n; j++){
            chess[i][j] = '1';  //在第i行第j列放置一个棋子
            if(judge(i,j)) Trial(i+1,n);
            chess[i][j] = '0';  //移走第i行第j列的棋子
        }
    }
}

int main(){
    init();
    Trial(1,QUEEN);
    printf("%d\n",count);
    return 0;
}





















//typedef struct point{
//    int x;
//    int y;
//}Ponit;
//
//typedef struct node{
//    int data;
//    node *next;
//}Node;
//
//typedef struct stack{
//    node *top;
//    node *bottom;
//}Stack;
//
创建栈(栈底为空节点)
//Stack * create(){
//    Stack *s = (Stack*)malloc(sizeof(Stack));
//    s->top = (Node *)malloc(sizeof(Node));
//    s->top->next = NULL;
//    s->bottom = s->top;
//    return s;
//}
//
压栈
//void push(Stack *s, Point val){
//    Node *current = (Node*)malloc(sizeof(Node));
//    current->data = val;
//    current->next = s->top;
//    s->top = current;
//}
//
出栈
//void pop(Stack *s, Point *val){
//    *val = s->top->data;
//    Node *p = s->top;
//    s->top = s->top->next;
//    free(p);
//}
//
输出棋盘
//void print(Stack *s){
//    reset_board();
//    Node *p = s->top;
//    while(p!=s->bottom){
//        chess_board[p->data.x][p->data.y] = 1;
//        p = p->next;
//    }
//    printf("\n");
//}


  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值