[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;
    }
};

分析

經(jīng)典的N皇后問題,基本所有的算法書中都會包含的問題,經(jīng)典解法為回溯遞歸,一層一層的向下掃描,需要用到一個pos數(shù)組,其中pos[i]表示第i行皇后的位置,初始化為-1,然后從第0開始遞歸,每一行都一次遍歷各列,判斷如果在該位置放置皇后會不會有沖突,以此類推,當?shù)阶詈笠恍械幕屎蠓藕煤?,一種解法就生成了,將其存入結(jié)果res中,然后再還會繼續(xù)完成搜索所有的情況,

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

  • 背景 一年多以前我在知乎上答了有關LeetCode的問題, 分享了一些自己做題目的經(jīng)驗。 張土汪:刷leetcod...
    土汪閱讀 12,912評論 0 33
  • 校驗日期有效性,除了在代碼中內(nèi)置日歷數(shù)據(jù),還可以利用以下方法進行判斷,而且代碼更簡潔。經(jīng)過測試,在本地虛擬機執(zhí)行1...
    咕咕鷄閱讀 1,944評論 0 0
  • 明天,女兒在參加中學第一次月考,今天晚上回到家就是拼命寫,拼命背。冒雨特意為她買的喜歡吃的酸菜魚,也沒好好吃,放下...
    會飛的魚媽閱讀 494評論 1 0
  • 這是一個最好的時代,這是一個最壞的時代。 人們面前應有盡有,人們面前一無所有。 ” 早上七點開始,聲音越來越大的鬧...
    老衲養(yǎng)貓閱讀 192評論 0 0
  • 1. 一個朋友的故事。 快要結(jié)婚的小柔與男友的婚事暫時要擱置了。不問不知道,一問嚇一跳,原來兩家父母就婚禮彩禮這件...
    蘇繆閱讀 7,695評論 186 127

友情鏈接更多精彩內(nèi)容