Acwing 843. n-皇后问题
- 知识点
 - 题目描述
 - 思路讲解
 - 代码展示
 
知识点
- DFS
 - 剪枝
 
题目描述

思路讲解
代码展示
第一种搜索方式:
#include <iostream>
using namespace std;
const int N = 20;
int n;
char g[N][N];
bool col[N], dg[N * 2], udg[N * 2];
void dfs(int u) {
    if (u == n) {
        for (int i = 0; i < n; i++) puts(g[i]);
        puts("");
        return;
    }
    for (int i = 0; i < n; i++)
        if (!col[i] && !dg[u + i] && !udg[n - u + i]) {
            g[u][i] = 'Q';
            col[i] = dg[u + i] = udg[n - u + i] = true;
            dfs(u + 1);
            col[i] = dg[u + i] = udg[n - u + i] = 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;
}
 
更原始的搜索方式:按格子来,放还是不放?
#include <iostream>
using namespace std;
const int N = 10;
int n;
bool row[N], col[N], dg[N * 2], udg[N * 2];
char g[N][N];
void dfs(int x, int y, int s) {
    if (s > n) return;
    if (y == n) y = 0, x++;
    if (x == n) {
        if (s == n) {
            for (int i = 0; i < n; i++) puts(g[i]);
            puts("");
        }
        return;
    }
    // 不放皇后
    g[x][y] = '.';
    dfs(x, y + 1, s);
    // 放皇后
    if (!row[x] && !col[y] && !dg[x + y] && !udg[x - y + n]) {
        row[x] = col[y] = dg[x + y] = udg[x - y + n] = true;
        g[x][y] = 'Q';
        dfs(x, y + 1, s + 1);
        g[x][y] = '.';
        row[x] = col[y] = dg[x + y] = udg[x - y + n] = false;
    }
}
int main() {
    cin >> n;
    dfs(0, 0, 0);
    return 0;
}
                


![排序---P1012 [NOIP1998 提高组] 拼数](https://img-blog.csdnimg.cn/6a4a35c6eaaf4767807c6c4c1b1f8c15.png)









![[中间件~大厂面试题] 腾讯三面,40亿的QQ号如何去重](https://img-blog.csdnimg.cn/556212602ecf49d79aa1af1a91b80033.png)





