Sunday, September 7, 2014

Leetcode: N-Queens II @Python

See N-Queens I.
class Solution:
    # @return an integer
    def under_attack(self,col, queens):
        return col in queens or any(abs(col - x) == len(queens)-i for i,x in enumerate(queens))
            
    def solve(self,n):
        solutions = [[]]
        for row in range(n):
            solutions = (solution+[i] for solution in solutions for i in range(n) if not self.under_attack(i, solution))
        return solutions

    def totalNQueens(self, n):
        return len(list(self.solve(n)))
      

No comments :

Post a Comment