首页 > 代码库 > 八皇后问题

八皇后问题

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 #define N 8
 4 bool matrix[N][N] = {0};
 5 void Print(bool m[N ][N ]){
 6     static int count = 1;
 7     printf("Case %d:\n", count++);
 8     for (int i = 0; i < N; i++) {
 9         for (int j = 0; j < N; j++)
10             m[i][j]==1?printf("Q") : printf(".");
11         printf("\n");
12     }
13     printf("\n");
14 }
15 bool Safety(bool m[N][N], int row, int col)
16 {
17     for (int i = 0; i < row ; i++)
18     {
19          for (int j = 0; j < N; j++)
20                    if(m[i][j]==1&&(j==col||abs(row-i)==abs(col-j)))
21                 return false;
22     }
23     return true;
24 }
25 void BackTrack(const int i) {
26     if (i >=N)
27         Print(matrix);
28     else
29         for (int j = 0; j < N; ++j) {
30             matrix[i][j] = 1;
31             if(Safety(matrix,i,j))
32                          BackTrack(i + 1);
33             matrix[i][j] = 0;
34         }
35 }
36 int main(void)
37 {
38     BackTrack(0);
39     return 0;
40 }

 

八皇后问题