八皇后之回溯

#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
#define Row 8
#define Col 8
int m[Row][Col]={0};
int sum=0;

bool check(int row,int col)
{
    int i,j;
    if(row==0)
        return true;
    for(i=0;i<row;i++)
        if(m[i][col]==1)
        return false;
    i=row-1;
    j=col-1;
    while(i>=0&&j>=0)
    {
        if(m[i][j]==1)
            return false;
        i--;
        j--;
    }
    i=row-1;
    j=col+1;
    while(i>=0&&j<Col)
    {
        if(m[i][j]==1)
            return false;
        i--;
        j++;
    }
    return true;
}
void output()
{
	 int i,j;
	 sum++;
	 printf("sum=%d\n",sum);
	 for(i=0;i<Row;i++)
	 {
		 for(j=0;j<Col;j++)
		 {
			 printf("%d ",m[i][j]);
		 }
		 printf("\n");
	 }
}
void solve(int row)
{
    if(row==Row)
        output();
    else
    {
        for(int i=0;i<Col;i++)
        {
            m[row][i]=1;
            if(check(row,i)==true)
            {
                solve(row+1);
            }
            m[row][i]=0;
        }
    }
}
int main()
{
    solve(0);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_38588998/article/details/81330015
今日推荐