Python Backtracking Solution


  • 0
    R
    class Solution(object):
        def __init__(self):
            self.tot = 0
            self.vis = [ dict() for _ in range(3)]
        
        def totalNQueens(self, n):
            """
            :type n: int
            :rtype: int
            """
            self.search(0, n)
            
            return self.tot
            
        def search(self, m, n):
            if m == n: 
                self.tot += 1
            else:
                for i in range(n):
                    if not self.vis[0].get(i, 0) and not self.vis[1].get(m + i, 0) and not self.vis[2].get(i - m, 0):
                        self.vis[0][i] = self.vis[1][m + i] = self.vis[2][i - m] = 1
                        self.search(m+1, n)
                        self.vis[0][i] = self.vis[1][m + i] = self.vis[2][i - m] = 0
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.