经典的问题,不过以前没有做过,今天动手写了一个,效率不是很高,但思想是有一点的,最主要是判断斜线的方法,用x+y和x-y来判断。
1: #include <iostream>
2:
3: using namespace std;
4: #define N 8
5:
6: void show(int A[N][N])
7: {
8: static int count = 0;
9: cout << ++count << endl;
10: for (int i = 0; i < N; i++)
11: {
12: for (int j = 0; j < N; j++)
13: {
14: if (A[i][j] == 1)
15: {
16: cout << "W ";
17: }
18: else
19: {
20: cout << "- ";
21: }
22: }
23: cout << endl;
24: }
25: cout << endl;
26: }
27:
28: bool check(int A[N][N], int x, int y)
29: {
30: int sum = x + y;
31: int sub = x - y;
32: for (int i = 0; i < N; i++)
33: {
34: if (x != i && A[i][y] == 1)
35: {
36: return false;
37: }
38: for (int j = 0; j < N; j++)
39: {
40: if (j == y)
41: {
42: continue;
43: }
44: if (A[x][j] == 1)
45: {
46: return false;
47: }
48: if (i + j == sum && A[i][j] == 1)
49: {
50: return false;
51: }
52: if (i - j == sub && A[i][j] == 1)
53: {
54: return false;
55: }
56: }
57: }
58:
59: return true;
60: }
61:
62: void putQueen(int A[N][N], int row)
63: {
64: if (row >= N)
65: {
66: show(A);
67: return;
68: }
69:
70: for (int i = 0; i < N; i++)
71: {
72: A[row][i] = 1;
73:
74: if (check(A, row, i) != false)
75: {
76: putQueen(A, row + 1);
77: }
78:
79: A[row][i] = 0;
80: }
81:
82: return;
83: }
84:
85: void run(int x[N][N])
86: {
87: putQueen(x, 0);
88: }
89:
90: int main()
91: {
92: int X[N][N] = {0};
93: run(X);
94: system("pause");
95: return 0;
96: }