python solution similar to n queens


  • 0
    A
    class Solution(object):
        """
        ref: https://youtu.be/xouin83ebxE
        """
        def totalNQueens(self, n):
            count = [0]
            positions = [None for i in range(n)]
            self.total(n, 0, positions, count)
            
            return count[0]
            
        def total(self, n, row, positions, count):
            if row == n:
                count[0] += 1
                return
        
            for col in range(n):
                found_safe = True
                
                for queen in range(row):
                    if positions[queen][1] == col or \
                       positions[queen][0] - positions[queen][1] == row - col or \
                       positions[queen][0] + positions[queen][1] == row + col:
                           found_safe = False
                           break
                       
                if found_safe:
                    positions[row] = (row, col)
                    self.total(n, row + 1, positions, count)
    

Log in to reply
 

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