N-queens Problem

文章描述了一个使用回溯算法来解决N-Queens问题的C++代码实现。该问题是将N个皇后放置在N×N的棋盘上,使得任何两个皇后不能相互攻击。程序通过读取棋盘大小并初始化棋盘状态,然后用深度优先搜索策略探索所有可能的配置。对于每个皇后的位置,检查是否与已放置的皇后冲突,如果不冲突则放置皇后并递归处理下一行,否则回溯尝试其他位置。最后,所有有效的解决方案都会被输出到标准输出。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

n-queens problem

The n-queen problem refers to placing n queens on an n×n chessboard so that the queens cannot attack each other, that is, any two queens cannot be on the same row, column or slope.
Now given an integer n, please output all chess pieces that meet the conditions.

input format
A line containing the integer n.

output format
Each solution occupies n lines, and each line outputs a string of length n, which is used to represent the complete board state. Among them, . indicates that the state of the square at a certain position is empty, and Q indicates that there is a queen on the square at a certain position. After outputting each scheme, output a blank line.

Note: There can be no extra spaces at the end of the line.
The order of the output schemes is arbitrary, as long as there are no repetitions and no omissions.

data range
1≤n≤9
Input sample:
4
Sample output:
.Q..
...Q
Q...
..Q.

..Q.
Q...
...Q
.Q..

Solution

The code above implements a backtracking algorithm to solve the N-Queens problem, which is to place N queens on an NxN chessboard such that no two queens threaten each other. The algorithm uses a depth-first search to explore all possible configurations of queens on the board.

The program first reads an integer n from standard input, which represents the size of the chessboard and the number of queens to be placed. It then initializes a 2D character array g of size nxn to represent the chessboard, where each cell is initially set to '.'. The program also initializes three boolean arrays col, dg, and udg of size n to keep track of which columns and diagonals are occupied by queens.

The program then calls the dfs function with u=0, which represents the current row being considered. The dfs function first checks if u is equal to n. If so, it means that a valid configuration of queens has been found, and the function outputs the chessboard to the console.

If u is less than n, the function enters a loop that iterates over all columns from 0 to n-1. For each column i, the function checks if the cell (u, i) is not threatened by any other queens. This is done by checking if the column i, diagonal u+i, and anti-diagonal n-u+i-1 are not already occupied by queens. If the cell is not threatened, the function places a queen at (u, i) by setting g[u][i] to 'Q', and updates the col, dg, and udg arrays to mark the corresponding column and diagonals as occupied. The function then recursively calls dfs with u+1 as the input.

After the recursive call to dfs returns, the function backtracks by removing the queen from (u, i) and updating the col, dg, and udg arrays to mark the corresponding column and diagonals as unoccupied. This allows the function to explore other possible configurations that start with a different column.

The program outputs all valid configurations of queens on the chessboard to standard output.

Overall, this code is a simple and elegant implementation.

#include <bits/stdc++.h>

using namespace std;

const int N = 20;

int n;
char g[N][N];
bool col[N], dg[N], udg[N];

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.tie(nullptr);
    cout.tie(nullptr);
    ios::sync_with_stdio(false);
    cin >> n;
    for (int i = 0; i < n; i ++ ) {
        for (int j = 0; j < n; j ++ ) {
            g[i][j] = '.';
        }
    }
    dfs(0);
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值