当前位置:网站首页>acwing 843. n-皇后问题
acwing 843. n-皇后问题
2022-07-06 22:04:00 【_刘小雨】
n−皇后问题是指将 n 个皇后放在 n×n 的国际象棋棋盘上,使得皇后不能相互攻击到,即任意两个皇后都不能处于同一行、同一列或同一斜线上。

现在给定整数 n,请你输出所有的满足条件的棋子摆法。
输入格式
共一行,包含整数 n。
输出格式
每个解决方案占 n 行,每行输出一个长度为 n 的字符串,用来表示完整的棋盘状态。
其中 . 表示某一个位置的方格状态为空,Q 表示某一个位置的方格上摆着皇后。
每个方案输出完成后,输出一个空行。
注意:行末不能有多余空格。
输出方案的顺序任意,只要不重复且没有遗漏即可。
数据范围
1≤n≤9
输入样例:
4
输出样例:
.Q…
…Q
Q…
…Q.
…Q.
Q…
…Q
.Q…
这题也是DFS, 可以根据全排列的
解法1:按行枚举 (也是跟上一题 全排列类似的)
可以作为模版进行记忆

#include <iostream>
using namespace std;
const int N = 20;
// bool数组用来判断搜索的下一个位置是否可行
// col列,dg对角线,udg反对角线
// g[N][N]用来存路径
int n;
char g[N][N];
bool col[N], dg[N], udg[N];
void dfs(int u) {
// u == n 表示已经搜了n行,故输出这条路径
if (u == n) {
for (int i = 0; i < n; i ++ ) puts(g[i]); // 等价于cout << g[i] << endl;
puts(""); // 换行
return;
}
// 枚举u这一行,搜索合法的列, // 这里可将行看成y, 列看成x
// 这里是枚举第u行, 第i 列, 是否放皇后, u= y, i = x 后 ===》 对角线就是 u + i、u - i + n
for (int i = 0; i < n; i ++ )
// 剪枝(对于不满足要求的点,不再继续往下搜索)
if (!col[i] && !dg[u + i] && !udg[n - i + u])
{
g[u][i] = 'Q';
col[i] = dg[u + i] = udg[n - i + u] = true;
dfs(u + 1);
col[i] = dg[u + i] = udg[n - i + u] = false;
g[u][i] = '.'; // 恢复现场
}
}
int main() {
cin >> n;
for (int i = 0; i < n; i ++ )
for (int j = 0; j < n; j ++ )
g[i][j] = '.';
dfs(0);
return 0;
}
方法2: 按照每个元素进行枚举
每个位置都有2种情况,放还是不放,总共就有n2
时间复杂度: O(2的n2次方), 打不出来了,见谅
原理图: 就类似这样画下去
思路: 按照每个位置放不放的步骤一点一点进行搜索。
code:
// 不同搜索顺序 时间复杂度不同 所以搜索顺序很重要!
#include <iostream>
using namespace std;
const int N = 20;
int n;
char g[N][N];
bool row[N], col[N], dg[N], udg[N]; // 因为是一个个搜索,所以加了row
// s表示已经放上去的皇后个数
void dfs(int x, int y, int s)
{
// 处理超出边界的情况, 这个是直接一行进行放还是不放, 一行走完了,跳到下一行开始
if (y == n) y = 0, x ++ ;
if (x == n) {
// x==n说明已经枚举完n^2个位置了
if (s == n) {
// s==n说明成功放上去了n个皇后
for (int i = 0; i < n; i ++ ) puts(g[i]);
puts("");
}
return;
}
// 分支1:放皇后
if (!row[x] && !col[y] && !dg[x + y] && !udg[x - y + n]) {
g[x][y] = 'Q';
row[x] = col[y] = dg[x + y] = udg[x - y + n] = true;
dfs(x, y + 1, s + 1);
row[x] = col[y] = dg[x + y] = udg[x - y + n] = false;
g[x][y] = '.';
}
// 分支2:不放皇后
dfs(x, y + 1, s);
}
int main() {
cin >> n;
for (int i = 0; i < n; i ++ )
for (int j = 0; j < n; j ++ )
g[i][j] = '.';
dfs(0, 0, 0);
return 0;
}
边栏推荐
- 主设备号和次设备号均为0
- 软件测试之网站测试如何进行?测试小攻略走起!
- C # use Siemens S7 protocol to read and write PLC DB block
- 数学分析_笔记_第10章:含参变量积分
- [written to the person who first published the paper] common problems in writing comprehensive scientific and Technological Papers
- See Gardenia minor
- [multi threading exercise] write a multi threading example of the producer consumer model.
- Gpt-3 is a peer review online when it has been submitted for its own research
- Mathematical analysis_ Notes_ Chapter 10: integral with parameters
- 2022 electrician cup question B analysis of emergency materials distribution under 5g network environment
猜你喜欢

Optimization of channel status offline of other server devices caused by easycvr cluster restart
![[team learning] [34 issues] scratch (Level 2)](/img/29/8383d753eedcffd874bc3f0194152a.jpg)
[team learning] [34 issues] scratch (Level 2)

EasyCVR平台接入RTMP协议,接口调用提示获取录像错误该如何解决?

Practice Guide for interface automation testing (middle): what are the interface testing scenarios
![[team learning] [phase 34] Baidu PaddlePaddle AI talent Creation Camp](/img/eb/9aed3bbbd5b6ec044ec5542297f3c6.jpg)
[team learning] [phase 34] Baidu PaddlePaddle AI talent Creation Camp

In cooperation with the research team of the clinical trial center of the University of Hong Kong and Hong Kong Gangyi hospital, Kexing launched the clinical trial of Omicron specific inactivated vacc

Deeply cultivate the developer ecosystem, accelerate the innovation and development of AI industry, and Intel brings many partners together

SSM+JSP实现企业管理系统(OA管理系统源码+数据库+文档+PPT)

这项15年前的「超前」技术设计,让CPU在AI推理中大放光彩

The most complete deployment of mongodb in history
随机推荐
Why does WordPress open so slowly?
Digital chemical plant management system based on Virtual Simulation Technology
Fix the problem that the highlight effect of the main menu disappears when the easycvr Video Square is clicked and played
Common methods of list and map
过气光刻机也不能卖给中国!美国无理施压荷兰ASML,国产芯片再遭打压
Unity3d can change colors and display samples in a building GL material
[multi threading exercise] write a multi threading example of the producer consumer model.
英特尔与信步科技共同打造机器视觉开发套件,协力推动工业智能化转型
Data security -- 12 -- Analysis of privacy protection
Up to 5million per person per year! Choose people instead of projects, focus on basic scientific research, and scientists dominate the "new cornerstone" funded by Tencent to start the application
What is CGI, IIS, and VPS "suggested collection"
Kotlin Compose Text支持两种颜色
How to conduct website testing of software testing? Test strategy let's go!
NTU notes 6422quiz review (1-3 sections)
ACL2022 | 分解的元学习小样本命名实体识别
機器人(自動化)課程的持續學習-2022-
Digital chemical plants realize the coexistence of advantages of high quality, low cost and fast efficiency
Optimization of channel status offline of other server devices caused by easycvr cluster restart
[coded font series] opendyslexic font
AI表现越差,获得奖金越高?纽约大学博士拿出百万重金,悬赏让大模型表现差劲的任务