[Leetcode] 59. 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.."]
]

解题之法

class Solution {
public:
    vector<vector<string> > solveNQueens(int n) {
        vector<vector<string> > res;
        vector<int> pos(n, -1);
        solveNQueensDFS(pos, 0, res);
        return res;
    }
    void solveNQueensDFS(vector<int> &pos, int row, vector<vector<string> > &res) {
        int n = pos.size();
        if (row == n) {
            vector<string> out(n, string(n, '.'));
            for (int i = 0; i < n; ++i) {
                out[i][pos[i]] = 'Q';
            }
            res.push_back(out);
        } else {
            for (int col = 0; col < n; ++col) {
                if (isValid(pos, row ,col)) {
                    pos[row] = col;
                    solveNQueensDFS(pos, row + 1, res);
                    pos[row] = -1;
                }
            }
        }
    }
    bool isValid(vector<int> &pos, int row, int col) {
        for (int i = 0; i < row; ++i) {
            if (col == pos[i] || abs(row - i) == abs(col - pos[i])) {
                return false;
            }
        }
        return true;
    }
};

分析

经典的N皇后问题,基本所有的算法书中都会包含的问题,经典解法为回溯递归,一层一层的向下扫描,需要用到一个pos数组,其中pos[i]表示第i行皇后的位置,初始化为-1,然后从第0开始递归,每一行都一次遍历各列,判断如果在该位置放置皇后会不会有冲突,以此类推,当到最后一行的皇后放好后,一种解法就生成了,将其存入结果res中,然后再还会继续完成搜索所有的情况,

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

相关阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 14,357评论 0 33
  • 校验日期有效性,除了在代码中内置日历数据,还可以利用以下方法进行判断,而且代码更简洁。经过测试,在本地虚拟机执行1...
    咕咕鷄阅读 5,803评论 0 0
  • 明天,女儿在参加中学第一次月考,今天晚上回到家就是拼命写,拼命背。冒雨特意为她买的喜欢吃的酸菜鱼,也没好好吃,放下...
    会飞的鱼妈阅读 3,118评论 1 0
  • 这是一个最好的时代,这是一个最坏的时代。 人们面前应有尽有,人们面前一无所有。 ” 早上七点开始,声音越来越大的闹...
    老衲养猫阅读 1,396评论 0 0
  • 1. 一个朋友的故事。 快要结婚的小柔与男友的婚事暂时要搁置了。不问不知道,一问吓一跳,原来两家父母就婚礼彩礼这件...
    苏缪阅读 12,186评论 186 127

友情链接更多精彩内容