8皇后问题

 1 //8皇后问题
 2 #include <stdio.h>
 3 int res=0;
 4 int a[8][8]={0};
 5 //检查放在此位置是否与上面的行冲突
 6 int check(int i,int j)
 7 {
 8     int x,y;
 9     for(x=i-1;x>=0;x--)if(a[x][j]==1)return 0;
10     for(y=j-1;y>=0;y--)if(a[i][y]==1)return 0;
11     for(x=i-1,y=j-1;x>=0&&y>=0;x--,y--)if(a[x][y]==1)return 0;
12     for(x=i-1,y=j+1;x>=0&&y<8;x--,y++)if(a[x][y]==1)return 0;
13     return 1;
14 }
15 //按行放 每行放一个
16 void dfs(int row)
17 {
18     if(row==8)
19     {
20         res++;
21         return;
22     }
23     int col;
24     for(col=0;col<8;col++)
25     {
26         if(check(row,col))
27         {
28             a[row][col]=1;
29             dfs(row+1);
30             a[row][col]=0;
31         }
32     }
33 }
34 int main()
35 {
36     dfs(0);
37     printf("%d
",res);
38     return 0;
39 }
原文地址:https://www.cnblogs.com/lancelee98/p/13357305.html