leetcode#52 N queensⅡ

來源:互聯網
上載者:User

標籤:說明   img   攻擊   輸出   image   如何   color   研究   並且   

皇后問題研究的是如何將 n 個皇后放置在 n×n 的棋盤上,並且使皇后彼此之間不能相互攻擊。

為 8 皇后問題的一種解法。

給定一個整數 n,返回 n 皇后不同的解決方案的數量。

樣本:

輸入: 4輸出: 2解釋: 4 皇后問題存在如下兩個不同的解法。[ [".Q..",  // 解法 1  "...Q",  "Q...",  "..Q."], ["..Q.",  // 解法 2  "Q...",  "...Q",  ".Q.."]]

class Solution {public:    int totalNQueens(int n)     {        return queen(0,0,0,0,0,n);           }    //l,r,d是左右豎線的控制範圍    int queen(int answer, int deep, int l, int d,int r,int n)    {        if (deep == n)//deep當前深度==皇后數,我們按行填皇后,所以deep其實還代表行數0-7.8說明已填滿n皇后            return answer + 1;        for (int i = 0; i < n; ++i)//再當前deep依次放入皇后        {                       if (((1 << i) & l) || ((1 << i)&d) || ((1 << i)&r))                continue;            answer = queen(answer, deep + 1, (l << 1) | (1 << (i + 1)), d | (1 << i), (r >> 1) | (1 <<( i - 1)),n);            }        return answer;    }};

 

leetcode#52 N queensⅡ

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.