n皇后问题

#include "iostream.h"
#include "string.h"
#include "math.h"
const int col=4;//4 columns 
int r[col];//r[i]represents for the r[i]-th column of i-th row
bool fit(int row)
{
    for (int i=0;i<row ;i++)
        if (r[i]==r[row]||abs(i-row)==abs(r[i]-r[row]))
            return 0;
        return 1;
}
void dfs(int row)//row starts from 0
{
    if (row==col)
    {
        for (int j=0;j<col;j++)
            cout<<r[j]<<'\t';
        cout<<endl;return;
    }
    
    for (int i=0;i<col;i++)
    {
        r[row]=i;
        if (fit(row))//不符合要求的就不会深入了
            dfs(row+1);
        //r[row]=-1;//置位
    }
}

void main()
{ 
    dfs(0);
}

 

posted on 2017-03-09 09:29  ewitt  阅读(73)  评论(0编辑  收藏  举报

导航