#include <algorithm>
#include <cmath>
#include <cstring>
#include <fstream>
#include <iostream>
#include <istream>
#include <iterator>
#include <list>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <string>
#include <utility>
#include <vector>
using namespace std;
/*
CLion 使用提示 :
批量注释代码 => Ctrl + shift + /
格式化代码 => option + command + L
补全语句 => Shift + command + return
生成构造器,getter和setter方法等 => control + return
行注释 => control + /
块注释 => control + shift + c
*/
constexpr const unsigned SIZE = 100;
int n = 0, x[SIZE], sum = 0;
vector<vector<string>> ans = // ?
{
{"!", "!", "!", "!", "!", "!", "!", "!", "!"},
{"!", "x", "x", "x", "x", "x", "x", "x", "x"},
{"!", "x", "x", "x", "x", "x", "x", "x", "x"},
{"!", "x", "x", "x", "x", "x", "x", "x", "x"},
{"!", "x", "x", "x", "x", "x", "x", "x", "x"},
{"!", "x", "x", "x", "x", "x", "x", "x", "x"},
{"!", "x", "x", "x", "x", "x", "x", "x", "x"},
{"!", "x", "x", "x", "x", "x", "x", "x", "x"},
{"!", "x", "x", "x", "x", "x", "x", "x", "x"}
};
void initString() {
ans = {
{"!", "!", "!", "!", "!", "!", "!", "!", "!"},
{"!", "x", "x", "x", "x", "x", "x", "x", "x"},
{"!", "x", "x", "x", "x", "x", "x", "x", "x"},
{"!", "x", "x", "x", "x", "x", "x", "x", "x"},
{"!", "x", "x", "x", "x", "x", "x", "x", "x"},
{"!", "x", "x", "x", "x", "x", "x", "x", "x"},
{"!", "x", "x", "x", "x", "x", "x", "x", "x"},
{"!", "x", "x", "x", "x", "x", "x", "x", "x"},
{"!", "x", "x", "x", "x", "x", "x", "x", "x"}
};
}
void printSolution() {
vector<int> v;
v.push_back(0);//随便推入1个元素,然后实际上有用的元素是下标从1开始的
for (int i = 1; i <= n; ++i) {
for (int j = 1; j <= n; ++j) {
ans[i][j] = "x";
}
}
for (int i = 1; i <= n; ++i) {
ans[i][x[i]] = "√";
}
for (int i = 1; i <= n; ++i) {
for (int j = 1; j <= n; ++j) {
printf("%s", ans[i][j].c_str());
}
printf("\n");
}
}
bool Place(int k) {
for (int j = 1; j < k; ++j) {
if (abs(k - j) == abs(x[j] - x[k]) || x[j] == x[k]) {
return false;
}
}
return true;
}
void BackTract(int t) {
if (t > n) {
int w = sum++;
printf("第%d个解\n" , w+1);
printSolution();
printf("\n");
} else {
for (int i = 1; i <= n; ++i) {
x[t] = i;//第t个皇后放在第i列
if (Place(t)) {
BackTract(t + 1);
}
}
}
}
void solution() {
unsigned T = 0;
while (true) {
printf("请输入一个正整数T,代表运行算法T次\n");
scanf("%d", &T);
for (int i = 1; i <= T; ++i) {
printf("请输入皇后个数n\n");
scanf("%d", &n);
BackTract(1);
}
}
}
int main() {
solution();
return 0;
}
n皇后-输出所有情况C++
最新推荐文章于 2023-12-19 15:37:14 发布