functional python solution


  • 1
    B
    class Solution(object):
        def solveNQueens(self, n):
            """
            :type n: int
            :rtype: List[List[str]]
            """
            def placeQueens(k):
                if k == 0:
                    yield []
                else:
                    for queens in placeQueens(k-1):
                        for col in xrange(n):
                            if isSafe(col, queens):
                                yield queens + [col]
        
            def isSafe(col, others):
                row = len(others)
                othersWithRow = zip(range(row), others)
                return all(not attacked((row, col), other) for other in othersWithRow)
                    
            def attacked(q1, q2):
                return q1[1] == q2[1] or abs(q1[0]-q2[0]) == abs(q1[1]-q2[1])
        
            def toString(solution):
                string = [['.' for i in xrange(n)] for j in xrange(n)]
                for i in xrange(n):
                    string[i][solution[i]] = 'Q'
                return [''.join(each) for each in string]
        
            return [toString(solution) for solution in placeQueens(n)]
    

Log in to reply
 

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