8皇后问题
超简单的回溯题,但两个月前我都不敢直视,今天又突然想起来,十分钟就搞定了。。。
#include <iostream>
#include <iostream>
using namespace std;
static int tot=0;
void search_q(int cur,int* p,int n)
{
int i,j;
if(cur==n)
{
tot++;
cout<<tot<<":";
for(i=0;i<n;i++)
cout<<p;
cout<<endl;
}
else for(i=0;i<n;i++)
{
int ok=1;
p[cur]=i;
for(j=0;j<cur;j++)
{
if(p[cur]==p[j]||p[cur]+cur==p[j]+j||p[cur]-cur==p[j]-j)
{
ok=0;
break;
}
}
if(ok) search_q(cur+1,p,n);
}
}
int main()
{
int arr[8][8];
int c[8];
search_q(0,c,8);
return 0;
}
共92解:
1:04752613
2:05726314
3:06357142
4:06471352
5:13572064
6:14602753
7:14630752
8:15063724
9:15720364
10:16257403
11:16470352
11:16470352
12:17502463
13:20647135
14:24170635
15:24175360
16:24603175
17:24730615
18:25147063
19:25160374
20:25164073
21:25307461
22:25317460
23:25703641
24:25704613
25:25713064
26:26174035
27:26175304
28:27360514
29:30471625
30:30475261
31:31475026
32:31625704
33:31625740
34:31640752
35:31746025
36:31750246
37:35041726
38:35716024
39:35720641
40:36074152
41:36271405
42:36415027
43:36420571
44:37025164
45:37046152
46:37420615
47:40357162
48:40731625
49:40752613
50:41357206
51:41362750
52:41506372
53:41703625
54:42057136
55:42061753
56:42736051
57:46027531
58:46031752
59:46137025
60:46152037
61:46152073
62:46302751
63:47302516
64:47306152
65:50417263
66:51602473
67:51603742
68:52064713
69:52073164
70:52074136
71:52460317
72:52470316
73:52613704
74:52617403
75:52630714
76:53047162
77:53174602
78:53602417
79:53607142
80:57130642
81:60275314
82:61307425
83:61520374
84:62057413
85:62714053
86:63147025
87:63175024
88:64205713
89:71306425
90:71420635
91:72051463
92:73025164