二维数组实现八皇后问题

 之前关八皇后的问题全部使用的是一维数组进行实现(http://www.cnblogs.com/SeaSky0606/p/4604955.html),现改一种数据存储方式,按照8x8的二维棋盘存储皇后。基本逻辑不变,可参见如下代码:
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<string>
#include<cmath>
#define N 8
int q[N][N],cnt=0;

void dfs(int x);
void placeon(int x,int y);
void takeout(int x,int y);
int canplace(int x,int y);
void ps();

int main(){
    dfs(0);
    printf("There are %d schema(s) in total!",cnt);
    return 0;
}
void dfs(int x){
    if(x==N){
        cnt++;
        ps();
    }else{
        for(int i=0;i<N;i++) if(canplace(x,i)){
            placeon(x,i);
            dfs(x+1);
            takeout(x,i);
        }
    }
}
void placeon(int x,int y){
    q[x][y]=1;
}
void takeout(int x,int y){
    q[x][y]=0;
}

//key
int canplace(int x,int y){
    for(int i=1;i<=x;i++){
        if((y+i<N &&(q[x-i][y+i]==1)) ||(y-i>=0 && (q[x-i][y-i]==1)) || q[x-i][y]==1){
            return 0;
        }
    }
    return 1;
}
void ps(){
    for(int i=0;i<N;i++){
        for(int j=0;j<N;j++){
            if(q[i][j]==1)printf("A");
            else
                printf(".");

        }
        printf("\n");
    }
    printf("\n");
}
posted @ 2016-04-30 15:14  Sea_Sky  阅读(1227)  评论(0编辑  收藏  举报

转载请注明出处! About me