1 #include <iostream>
2 #include <vector>
3 #include <string>
4 #include <queue>
5 #include <stack>
6 #include <algorithm>
7 using namespace std;
8
9 class Solution {
10 public:
11 int count = 0; //count:统计解法个数
12 string chess[8][8]; //chess:8*8棋盘
13 string line; //line:临时变量,将一行的状况保存并循环输入到whole_chess里
14 vector<string> whole_chess; //whole_chess:临时变量,将一种解法的整个棋盘输入到out里
15 vector<vector<string>> out; //out:输出的解法
16
17 //改变solveNQueen函数,返回out,就可以查看解法的详细
18
19 int solveNQueens(int n) { //函数入口
20
21 //空棋盘的初始化
22 for (int y = 0; y < 8; y++) {
23 for (int x = 0; x < 8; x++) {
24 chess[y][x] = ".";
25 }
26 }
27 //从第 1 行开始放棋子
28 backtrack_queen(0);
29 return count;
30 }
31
32 void backtrack_queen(int y) { //原理:通过不断使y自增1,进入backtrack_queen(y+1)里,直到y==8,则有解并记录解
33 if (y == 8) { //直到y==8,则有解并记录解
34 for (int y = 0; y < 8; y++) {
35
36 line.clear(); //将一行的状况保存并循环输入到whole_chess里
37 for (int x = 0; x < 8; x++) { //
38 line.append(chess[y][x]); //
39 } //
40 whole_chess.push_back(line); //
41 }
42 out.push_back(whole_chess); //将一种解法的整个棋盘输入到out里
43 whole_chess.clear(); //
44
45 count++; //解法计数 +1
46 return;
47 }
48
49 for (int x = 0; x < 8; x++) {
50 if (judge(y, x)) {
51 chess[y][x] = "Q"; //先将本次的棋子置为Q皇后,测试有没有解
52 backtrack_queen(y + 1); //通过不断地传递 y+1 的参数,逐层深入棋盘。如果此时传入的参数==8,则为一个解。
53 chess[y][x] = "."; //还原上一个摆放的棋子
54 }
55 }
56 }
57
58 //判断 行 列 斜行 是否冲突的函数
59 bool judge(int y, int x) {
60 //判断行冲突
61 for (int b = 0; b < x; b++) {
62 if (chess[y][b] == "Q")
63 return false;
64 }
65 //判断列冲突
66 for (int a = 0; a < y; a++) {
67 if (chess[a][x] == "Q")
68 return false;
69 }
70 //判断左上斜行冲突
71 for (int a = y - 1, b = x - 1; a >= 0 && b >= 0; a--, b--) {
72 if (chess[a][b] == "Q")
73 return false;
74 }
75 //判断右上斜行冲突
76 for (int a = y - 1, b = x + 1; a >= 0 && b < 8; a--, b++) {
77 if (chess[a][b] == "Q")
78 return false;
79 }
80 return true;
81 }
82 };
83
84
85 int main()
86 {
87 Solution s;
88 cout << "摆放棋盘的方法的种数:" <<s.solveNQueens(8);
89 cout << endl;
90 }