LeetCode-51-N-Queens 八皇后问题dfs


class Solution(object):
    N=0
    P=[]
    ans=[]
    def solveNQueens(self, n):
        """
        :type n: int
        :rtype: List[List[str]]
        """
        self.N=n
        self.ans=[]
        self.dfs(n,0)

        return self.ans
        #print self.ans
        
        
    def dfs(self, n, raw):
        if(n==0):
            curans=[['.' for i in range(self.N)]for j in range(self.N)]
            for i in range(self.N):
                curans[self.P[i]/self.N][self.P[i]%self.N]='Q'
            for i in range(self.N):
                curans[i]="".join(curans[i])
            self.ans.append(curans)
            #self.ans.append(self.P[:])
        for i in range(raw*self.N,raw*self.N+self.N):
            if self.judge(i):
                self.P.append(i)
                self.dfs(n-1,raw+1)
                self.P.pop()
                
    def judge(self,p):
        x=p/self.N
        y=p%self.N
        for i in range(len(self.P)):
            curx=self.P[i]/self.N
            cury=self.P[i]%self.N
            if curx==x or cury==y or abs(curx-x)==abs(cury-y):
                return False
        return True


你可能感兴趣的:(Leetcode)