八皇后问题-打印解

 1 #include<cstdio>
 2 #include<queue>
 3 #include<iostream>
 4 #include <utility>
 5 #include <algorithm>
 6 #include<vector>
 7 using namespace std;
 8 
 9 int C[10];//暂时记录每行的皇后位置
10 const int n = 8;//皇后总数
11 
12 char P[8][8]; //记录棋盘是否可以落
13 int N = 1;
14 
15 void ewq(int i, int x, int y)//在xy的为周围加i
16 {
17     for (int j = 0; j < n; j++)
18     {
19         P[x][j]+=i;
20         P[j][y]+=i;
21         if (x-y+j>=0&& n > x - y + j)
22         {
23             P[x - y + j][j]+=i;
24         }
25         if (x+y-j >= 0&& n > x+y-j)
26         {
27             P[x+y-j][j]+=i;
28         }
29     }
30     P[x][y] -= 3*i;
31 }
32 
33 void pri()//打印解
34 {
35     for (int i = 0; i < n; i++)
36     {
37         for (int j = 0; j < n; j++)
38             printf("%d ", ((C[i] == j) ? 1 : 0));
39         printf("\n");
40     } 
41     printf("\n");
42 }
43 
44 void pri_1()//第二种打印
45 {
46     printf("No. %d\n", N++);
47     for (int i = 0; i < n; i++)
48     {
49         for (int j = 0; j < n; j++)
50             printf("%d ", ((C[j] == i) ? 1 : 0));
51         printf("\n");
52     }
53 }
54 
55 void qwe(int cur)
56 {
57     for (int i = 0; i < n; i++)
58     {
59         if (!P[cur][i])//有位置
60         {
61             C[cur] = i;//标记位置
62             if (cur == n - 1)
63             {
64                 pri_1();
65                 continue;
66             }
67             ewq(1, cur, i);//写名字
68             qwe(cur + 1);
69             ewq(-1, cur, i);//取消名字
70         }
71     }
72 }
73 
74 
75 int main()
76 {
77     memset(P, 0, sizeof(P));
78     qwe(0);
79     return 0;
80 }

猜你喜欢

转载自www.cnblogs.com/li136/p/11616004.html
今日推荐