第一个八皇后

#include<iostream>
#include<stdio.h>
#define LOCAL
using namespace std;
int m[10][10]={0};
int num=0;
int check(int row,int column)//检查当前状态下能否放置
{
    int i,j;
    if(row==1) return 1;
    for(i=1;i<row;i++)//对同一列的棋盘进行检查
        if(m[i][column]==1) return 0;
    i=row-1;
    j=column-1;
    while(i>=1&&j>=1)对左上到当前点进行检查
    {
        if(m[i][j]==1) return 0;
        i--;j--;
    }
    i=row-1;
    j=column+1;
    while(i>=1&&j<=8)//对当前点到又上进行检查
    {
        if(m[i][j]==1) return 0;
        i--;
        j++;
    }
    return 1;//成功
}
void output()//输出
{
    int i,j;
    num++;
    cout<<"the NO."<<num<<endl;
    for(i=1;i<=8;i++)
    {
        for(j=1;j<=8;j++) cout<<m[i][j]<<" ";
        cout<<endl;
    }
    cout<<endl;
}
int place(int row)
{
    int j;
    for(j=1;j<=8;j++)//对当前row行的1-8进行尝试
    {
        m[row][j]=1;
        if(check(row,j)==1)//如果成功
        {
            if(row==8) output();//增加num,输出结果
            else place(row+1);//否则进入到下一行的搜索
        }
        m[row][j]=0;失败则的回溯到上一row行
    }
}
int main()
{
    #ifdef LOCAL
      freopen("data.out","w",stdout);
    #endif // LOCAL
    place(1);
    cout<<num<<endl;
    return 0;
}

posted @ 2013-12-18 17:50  ACalvin  阅读(211)  评论(0编辑  收藏  举报