My python solutions to N-Queens I & II, and a question.


  • 0
    Z

    For N-Queens I,

    def solveNQueens(self, n):
        res, myset = [], set()
        def dfs(i, tmp, myset):
            if i == n:
                grid = []
                for j in sorted(list(tmp), key = lambda x: x[0]):
                    grid.append('.'*j[1]+'Q'+'.'*(n-j[1]-1))
                res.append(grid)
                return
            for j in range(n):
                if ('a', i) not in myset and ('b', j) not in myset and ('c', i+j) not in myset and ('d', i-j) not in myset:
                    dfs(i+1, tmp + [(i,j)], myset | set([('a', i), ("b", j), ('c', i+j), ('d', i-j)]))
        dfs(0, [], myset)
        return res
    

    For N-Queens II,

    def totalNQueens(self, n):
        self.res, myset = 0, set()
        def dfs(i, tmp, myset):
            if i == n:
                self.res += 1
                return
            for j in range(n):
                if ('a', i) not in myset and ('b', j) not in myset and ('c', i+j) not in myset and ('d', i-j) not in myset:
                    dfs(i+1, tmp + [(i,j)], myset | set([('a', i), ("b", j), ('c', i+j), ('d', i-j)]))
        dfs(0, [], myset)
        return self.res
    

    Question:

    Why in N-Queens I "res" as a list is global, but in N-Queens II "res" as a variable is not global (so I have to use self.res). Is this a general rule in Python?


Log in to reply
 

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