Basic practice 2n queens problem - backtracking, greedy algorithm

/*
Basic practice 2n queens problem
Problem description
  Given an n*n chessboard, there are some positions on the chessboard where queens cannot be placed. Now we want to put n black queens
and , so that no two black queens are on the same row, column or diagonal, and no two
white queens are on the same row, in the same column or on the same diagonal. How many ways are there in total? n is less than or equal to 8.
Input
  format The first line of input is an integer n, which represents the size of the chessboard.
  Next n lines, each line contains n integers of 0 or 1. If an integer is 1, it means that the corresponding position can be put in the queen.
If an integer is 0, it means that the corresponding position cannot be put in the queen.
Output format
  Output an integer, indicating how many ways there are in total.
Sample Input
4
1 1 1 1
1 1 1 1 1 1
1 1 1
1 1 1
Sample Output
2
Sample Input
4
1 0 1 1
1 1 1 1 1
1 1 1 1
1 1 1
Sample Output
0
*/
#include<stdio.h>
int tongji(int  , int  , int [][8] , int ,int *);
int check(int , int  ,int ,int [][8] , int );
void shuru( int , int [][8]);


int main(void)
{
    int n ,sz[8][8];
    scanf("%d",&n);
    shuru( n , sz );
    int sum=0;
    printf("%d",tongji(n , 0 , sz , 2  ,&sum));
    return 0;
}
int tongji(int n , int x , int sz[][8] , int s ,int *sum)
{
    
    if( x == n )
    {
        if( s == 2 )
{
tongji(n , 0, sz, 3 , sum );
}
        else 
{
++ *sum ;
}
        return 0;
    }
    int i ;
    for(i = 0 ; i < n ; i ++)
    {
        if(sz[x][i] != 1)
{
continue;
}
        if(check(n , x , i , sz , s ))
{
sz[x][i]=s;
}
        else 
{
continue; }         tongji(n , x+1 , sz , s ,sum );         sz[x][i]=1;     }     return * sum; int check(int  n , int x ,int y ,int sz[][8] , int s) {     int i , j;     for( i = x-1 ; i >= 0 ; i --)     {         if(sz[i][y] == s) { return 0; }     }
















    for(i=x-1,j = y-1 ; i >= 0 && j >= 0; i -- , j --)
    {
        if(sz[i][j] == s)
{
return 0;
}
    }
    for(i = x-1,j = y+1;i >= 0 && j < n ; i -- , j ++)
    {
        if( sz[i][j]== s)
        {
        return 0;
}
    }
    return 1;
}
void shuru( int  n , int sz[][8])
{
int i , j ;
for( i = 0 ; i < n ; i ++)
    {
        for( j = 0 ; j < n ; j ++)
        {
            scanf("%d",&sz[i][j]);
        }
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324686778&siteId=291194637