[DFS]52. N-Queens II

  • 分類(lèi):DFS
  • 時(shí)間復(fù)雜度: O(n^2)

52. N-Queens II

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

N-Queen II

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

Example:


Input: 4

Output: 2

Explanation: There are two distinct solutions to the 4-queens puzzle as shown below.

[

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

 "...Q",

 "Q...",

 "..Q."],

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

 "Q...",

 "...Q",

 ".Q.."]

]

代碼:

方法:

class Solution:

    res=0
    
    def totalNQueens(self, n):
        """
        :type n: int
        :rtype: int
        """
        self.res=0
        if n==0:
            return res
        col=[True for i in range(n)]
        diag1=[True for i in range(2*n-1)]
        diag2=[True for i in range(2*n-1)]
        self.n_queens(0,n,col,diag1,diag2)
        return self.res

    def n_queens(self,y,n,col,diag1,diag2):
        if y==n:
            self.res+=1
            return
        for x in range(n):
            if not self.valid(x,y,n,col,diag1,diag2):
                continue
            self.updateBoard(x,y,n,False,col,diag1,diag2)
            self.n_queens(y+1,n,col,diag1,diag2)
            self.updateBoard(x,y,n,True,col,diag1,diag2)

    def updateBoard(self,x,y,n,isPut,col,diag1,diag2):
        col[x]=isPut
        diag1[x+y]=isPut
        diag2[x-y+(n-1)]=isPut

    def valid(self,x,y,n,col,diag1,diag2):
        return col[x] and diag1[x+y] and diag2[x-y+(n-1)]

討論:

1.一道經(jīng)典DFS題,我還是覺(jué)得自己有些智障的捋不清orz

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

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

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi閱讀 7,872評(píng)論 0 10
  • 我是一只剛上路的菜鳥(niǎo)會(huì)計(jì),在一家公司上班。 我前二十年都在做關(guān)于生產(chǎn)管理、辦公行政類(lèi)的工作。從東莞到華北的一個(gè)小縣...
    山中精靈閱讀 307評(píng)論 1 2
  • 8月21日晚至22日凌晨,市公安局交警支隊(duì)、高速支隊(duì)組織參戰(zhàn)交警、特警、交通路政、城管共計(jì)270余人,全市共出動(dòng)警...
    cf7b9e9335a4閱讀 177評(píng)論 0 0
  • 大學(xué)似乎真的是個(gè)特別容易讓人墮落的地方,當(dāng)初未進(jìn)入之前,你想著在大學(xué)你要干啥干啥,但當(dāng)你步入大學(xué)之后,一切似乎偏...
  • 離恨皇天也斷腸,咽成雨淚灑凄涼。 絮楊不忍楊花蕩,無(wú)奈雷風(fēng)偏作狂。 時(shí)雨霽,眺平陽(yáng),陰晴不定嘆無(wú)常。 悲歡離索長(zhǎng)思...
    稽首琉璃月閱讀 273評(píng)論 0 5

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