N皇后问题(基本的搜索法)

来源:互联网 发布:百胜厨叻沙拉面 知乎 编辑:程序博客网 时间:2024/05/17 22:15
/*
N后问题
*/


#include 
<stdio.h>
#include 
<math.h>

#define MAX 101

int total = 0;
char m[MAX][MAX];
 

int is_ok(int s,int i,int *a)
{
    
int j ;
    
for(j=1 ; j< s ; j++)
    
if( (abs(i-a[j]) == abs(s-j)) || (i == a[j])) /*按行填入,所以只要检查列和斜列是否有皇后即可*/
        
return 0 ;
    
return 1 ;
}


void nfind(int s,int n,int *a)
{
    
int i,p,q;

    
if( s > n)
    
{
        total 
++ ;
        printf(
"========The num of %d is ========== ",total); 
        
for(p=1 ; p<= n ; p++)
        
{
            
for(q=1; q<=n ; q++)
                printf(
"%c ",m[p][q]);
            printf(
" ");
        }

        
    }

    
else
    
{
        
for(i=1 ;i<= n; i++)
     
            
if(is_ok(s,i,a))
            

                 
                a[s]
=i ;
                m[s][i]
='O' ;
                nfind(s
+1,n,a);
                m[s][i]
='*' ;
             
            }

         
    }




}


int main(void)
{

    
int n ,a[MAX]={0};
    scanf(
"%d",&n);
    memset(m,
'*',sizeof(m));
    nfind(
1,n,a);
    printf(
" total=%d ",total);
    system(
"pause");
    
return 0;
}