Output Limit Exceeded - N-queens


  • 1
    Y

    following is my code and the result on my laptop. however, i got output limit exceeded error. So, there is 352 solutions to 9-queens problem, my solution should be correct.

    class Solution:
        # @return a list of lists of string
        def solveNQueens(self, n):
            allanswer = []
            answer = [n]*n
            self.solve(answer, 0, allanswer, n)
            # translate
            results = []
            for a in allanswer:
                res = [['.']*n for i in range(n)]
                for i in range(n):
                    res[a[i]][i] = 'Q'
                results.append(res)
            return results
    
        def solve(self, curr, col, save, dim):
            for i in range(0,dim):
                # put Q in (i, col), check if it fits
                if i in curr[:col]: # check row i of other columns
                    continue
                curr[col] = i
                fit = self.fit(curr,col,i,dim)
                if fit:
                    if col == dim-1:
                        save.append(list(curr))
                    else:
                        self.solve(curr, col+1, save, dim)
            curr[col] = dim
    
        def fit(self, curr, col, row,dim): # check diag only
            for i in range(1,col+1):
                t = curr[col-i]
                if t+i == row or t-i== row:
                    return False
            return True
    
    
    1:1:0.0
    2:0:0.0010020732879638672
    3:0:0.0
    4:2:0.001001119613647461
    5:10:0.006005048751831055
    6:4:0.02501702308654785
    7:40:0.0740509033203125
    8:92:0.29419994354248047
    9:352:1.373988151550293

Log in to reply
 

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