LeetCode 51 - N-Queens

本文介绍了一种解决N皇后问题的有效算法。通过递归回溯的方式,在N×N的棋盘上放置N个皇后,使得任意两个皇后不会互相攻击。代码实现中使用了布尔检查函数确保每一步操作都不会违反规则,并提供了所有可能的解决方案。

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

N-Queens

The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.

Given an integer n, return all distinct solutions to the n-queens puzzle.

Each solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both indicate a queen and an empty space respectively.

For example,
There exist two distinct solutions to the 4-queens puzzle:

[
 [".Q..",  // Solution 1
  "...Q",
  "Q...",
  "..Q."],

 ["..Q.",  // Solution 2
  "Q...",
  "...Q",
  ".Q.."]
]

My Code

class Solution {
public:
    bool inline check(vector<string>& str, int i, int j, int n)
    {
        for (int ii = 0; ii < i; ii++)
            if (str[ii][j] == 'Q')
                return true;

        for (int ii = i - 1, jj = j - 1; ii >= 0 && jj >= 0; ii--, jj--)
            if (str[ii][jj] == 'Q')
                return true;

        for (int ii = i - 1, jj = j + 1; ii >= 0 && jj < n; ii--, jj++)
            if (str[ii][jj] == 'Q')
                return true;

        return false;
    }

    void doSolve(vector<vector<string> >& strs, vector<string>& str, int i, int                                                                                              j, int n)
    {
        if (i == n || j == n)
            return;

        // false -> no clash
        bool flag = check(str, i, j, n);

        // Clash
        if (flag == true)
            doSolve(strs, str, i, j + 1, n);
        else
        {
            str[i][j] = 'Q';
            if (i == n - 1)
                strs.push_back(str);
            else
                doSolve(strs, str, i + 1, 0, n);
            str[i][j] = '.';
            doSolve(strs, str, i, j + 1, n);
        }


    }

    vector<vector<string> > solveNQueens(int n) {
        vector<string> str(n, string(n, '.'));
        vector<vector<string> > strs;
        doSolve(strs, str, 0, 0, n);

        return strs;
    }
};
Runtime: 8 ms

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

EnjoyCodingAndGame

愿我的知识,成为您的财富!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值