51.N皇后(回溯法)

题目
n 皇后问题研究的是如何将 n 个皇后放置在 n×n 的棋盘上,并且使皇后彼此之间不能相互攻击。

Queen

上图为 8 皇后问题的一种解法。

给定一个整数 n,返回所有不同的 n 皇后问题的解决方案。

每一种解法包含一个明确的 n 皇后问题的棋子放置方案,该方案中 'Q' 和 '.' 分别代表了皇后和空位。

示例:

输入: 4

输出: [
[".Q..", // 解法 1
"...Q",
"Q...",
"..Q."],

["..Q.", // 解法 2
"Q...",
"...Q",
".Q.."]
]

解释: 4 皇后问题存在两个不同的解法。

思路

#include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
    vector<vector<string>> solveNQueens(int n) {
        return convertToVectorString(solve(n), n);
    }
    vector<vector<int>> solve(int n)
    {
        vector<vector<int>> res;
        vector<int> cur;
        helpQ(res, cur, 0, n);
        return res;
    }
    void helpQ(vector<vector<int>>& res, vector<int> cur, int pos, int n)
    {
        if (pos == n)
        {
            res.push_back(cur);
        }
        else
        {
            for (int i = 0; i < n; i++)
            {
                cur.push_back(i);
                if (checkQ(cur))
                {
                    helpQ(res, cur, pos + 1, n);
                }
                cur.pop_back();
            }
        }
    }
    bool checkQ(vector<int> cur)
    {
        int size = cur.size(), loc = cur[size - 1];
        for (int i = 0; i < size - 1; i++)
        {
            if (cur[i] == loc)
            {
                return false;
            }
            else if (abs(cur[i] - loc) == abs(i - size + 1))//判断(cur[i] - loc)横向距离 和(i - (size - 1))纵向距离,即不在斜对角上
            {
                return false;
            }
        }
        return true;
    }
    vector<vector<string>> convertToVectorString(vector<vector<int>> res, int n)
    {
        vector<vector<string>> stingConvt;
        for (int i = 0; i < res.size(); i++)
        {
            vector<string> temp;
            for (int j = 0; j < n; j++)
            {
                string loc(n, '.');
                loc[res[i][j]] = 'Q';
                temp.push_back(loc);
            }
            stingConvt.push_back(temp);
        }
        return stingConvt;
    }
};

int main(int argc, char* argv[])
{
    int n = 4;
    auto res = Solution().solveNQueens(n);
    return 0;
}

我的博客即将同步至腾讯云+社区,邀请大家一同入驻:https://cloud.tencent.com/developer/support-plan?invite_code=30svdpg293400

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • n 皇后问题研究的是如何将 n 个皇后放置在 n×n 的棋盘上,并且使皇后彼此之间不能相互攻击。 上图为 8 皇后...
    vbuer阅读 1,882评论 0 0
  • 题目描述 The n-queens puzzle is the problem of placing n quee...
    JackpotDC阅读 5,916评论 0 49
  • 问题描述 n皇后问题是将n个皇后放置在n*n的棋盘上,皇后彼此之间不能相互攻击(不同行,不同列,不同对角线)。给定...
    Alfie20阅读 3,746评论 0 0
  • 后来,她就失明了,被老人家捡了回来。 胡笳刷的睁开眼,可是双眼无神。 她觉得,既然江寒想杀她,就不会令她轻易得救,...
    烨若春敷阅读 1,670评论 0 1
  • 迎面结实的撞了个叮咣,两个人把摩托车停在路边仔细端详各自的损坏。拐弯的递给直行的一支烟,点上,嘴里不停的喃喃着歉意...
    飞哥日记阅读 2,695评论 0 0

友情链接更多精彩内容