51N Queen

Title: Research queens problem is how to n  queens placed n × n on the board, and the queen can not attack each other to each other. Given an integer n, returns all solutions to different problems of the Queen of n. Each solution contains an explicit n pieces placed queens problem program, which the 'Q' and '' and a gap representing the queen.
Source: https: //leetcode-cn.com/problems/n-queens/

Act one: their own code for more than 90 percent

Ideas: the official reference solution, treatment backtracking framework of realization of the list again, the key is to meet the problems of the four conditions, the level is to use a for loop to traverse, will not be repeated, and two oblique with p q is achieved, with the vertical cols recorded, these four conditions is actually pruning conditions.

class Solution:
     DEF solveNQueens (Self, n-: int): 
        Results = []
         DEF BackTrack (Row = -1, COL = 0):
             # back termination condition, if the last line, indicating to find a solution, the storage 
            IF Row . 1-n-== : 
                Solution = []
                 for _, COL in the sorted (Queens): 
                    solution.append ( ' . ' * COL + ' Q ' + ' . ' * (n-- - COL. 1 )) 
                results.append ( Solution) 
                return
            Row + =. 1
             for COL in Range (n-):
                 # If equal to 0, indicating that can be put, 
                # IF condition here is to prune 
                IF cols [COL] + P [COL + Row] + Q [COL-Row] == 0 :
                     # placing a queen 
                    queens.add ((Row, COL))
                     # where cols effects even if the recording is actually to Queen vertical direction, 
                    # P, queen Q in order to record whether there is a two obliquely 
                    # horizontally using for loop through each set to 0 after the back end, so be sure there is no Queen 
                    # and because these objects are variable, the function back after the end of each call, change the value of value still exists, it needs to go back after the function plus SRE 0 program 
                    # and row and col are immutable objects, after each call back function will be restored value before calling 
                    cols [col]. 1 = 
                    P [col + row] =. 1
                    Q [COL -ROW] =. 1 
                    BackTrack (Row, COL) 
                    # After backtracking function, Queen just taken place, and the for loop continues, a next position is determined 
                    queens.remove ((Row, COL)) 
                    cols [COL] = 0 
                    P [COL + Row] = 0 
                    Q [COL - Row] = 0 
        cols = [0] * n-
         # P records the main diagonal direction, q records the sub diagonal direction 
        # P, q is observed by drawing out , the introduction of p, q is placed in order to distinguish the queen can not be placed on the diagonal direction Queen 
        P = [0] * (n-2 * -. 1 ) 
        Q = [0] * (n-2 * -. 1 )
         # because the list can not be append pop-tuple, where it is set by
        queens = set()
        backtrack()
        return results
if __name__ == '__main__':
    duixiang = Solution()
    ww = duixiang.solveNQueens(4)
    print('结果是:', ww)
View Code

Act II: The official solution, very clear ideas with a number of functions to achieve a modular

# 官网python代码
class Solution:
    def solveNQueens(self, n: int):
        def could_place(row, col):
            return not (cols[col] + hill_diagonals[row - col] + dale_diagonals[row + col])
        def place_queen(row, col):
            queens.add((row, col))
            cols[col] = 1
            hill_diagonals[row - col] = 1
            dale_diagonals[row + col] = 1
        def remove_queen(row, col):
            queens.remove((row, col))
            cols[col] = 0
            hill_diagonals[row - col] = 0
            dale_diagonals[row + col] = 0
        def add_solution():
            solution = []
            for _, col in sorted(queens):
                solution.append('.' * col + 'Q' + '.' * (n - col - 1))
            output.append(solution)
        def backtrack(row=0):
            for col in range(n):
                ifcould_place (Row, COL):
                    place_queen (Row, COL) 
                    IF Row +. 1 == n-: 
                        add_solution () 
                    the else : 
                        BackTrack (Row +. 1 )
                     # object is performed when the back end of this function returns the state before the call 
                    remove_queen (Row, COL) 
        cols = [ 0] * n- 
        hill_diagonals = [0] * (n-2 * -. 1 ) 
        dale_diagonals = [0] * (n-2 * -. 1 ) 
        Queens = SET () 
        Output = [] 
        BackTrack () 
        return Output
 the __name__IF == ' __main__ ' : 
    duixiang = Solution () 
    WW = duixiang.solveNQueens (. 4 )
     Print ( ' result: ' , WW)
View Code

 

Guess you like

Origin www.cnblogs.com/xxswkl/p/11968132.html