Subject description:
Method One: backtracking
class Solution: def totalNQueens(self, n: int) -> int: def backtrack(i,tmp,col,z_diagonal,i_diagonal): if i == n: nonlocal res res += 1 return for j in range(n): if j not in col and i+j not in z_diagonal and i-j not in i_diagonal: backtrack(i+1,tmp+[s[:j]+"Q"+s[j+1:]],col|{j},z_diagonal|{i+j},i_diagonal|{i-j}) s = "." * n res = 0 backtrack(0,[],set(),set(),set()) return res
Another: bit operation optimization: *
class Solution: DEF totalNQueens (Self, n-: int) -> int: DEF BackTrack (Row = 0, Hills = 0, next_row = 0, Dales = 0, COUNT = 0): "" " : type Row: current drop Queen line number : type hills: main diagonal occupancy [= 1 is occupied, unoccupied = 0] : next_row type: where the next line is occupied by the [= 1 is occupied, unoccupied = 0] : type Dales : occupancy times diagonal [= 1 is occupied, unoccupied = 0] : rtype: number of all feasible solutions "" " IF Row n ==: # If n queens have been placed COUNT = 1 + # cumulative feasible solution to the else : # current line available columns #! 0 and 1 represent the meanings of the meanings variables hills, next_row and dales are opposite # [1 = unoccupied, occupied = 0] free_columns Columns = & ~ (Hills | next_row | Dales) # find the next may be placed column Queen the while free_columns: # of free_columns of a '1' bit # in the column we put this Queen curr_column = - free_columns & free_columns # placing Queen # and eliminating the column corresponding to free_columns ^ = curr_column COUNT = BackTrack (row 1 + , (Hills | curr_column) << 1 , next_row | curr_column, (Dales | curr_column) >>. 1 , COUNT) return COUNT # board can be placed in all the columns, # i.e., bit representations of n '. 1' # bin (cols) = 0b1111 (n =. 4) , bin (cols) = 0b111 (n-=. 3) # [. 1 may be placed =] Columns = (n-<<. 1) -. 1 return BackTrack ()
another:
class Solution: DEF totalNQueens (Self, the n-: int) -> int: DEF the DFS (the n-: int, Row: int, cols: int, left: int, right: int): "" " depth-first search : param n: the number N of Queens : param row: depth of recursion : param cols: can attack columns : param left: on the left hatched columns can be attacked : param right: the right hatched columns may be attacked "" " IF Row> = n-: self.res + =. 1 return # get the current space available bits = (~ (cols | left | right)) & ((n-<<. 1) -. 1 ) # through available space whilebits: # acquires a position of P = & bits - bits the DFS (n-, Row +. 1, cols | P, (left | P) <<. 1, (right | P) >>. 1 ) bits = & bits (bits -. 1 ) IF Not (== n-1 or n-> = 4 ): # N queens problem only equal to when N is greater than or equal to 4 1 solution only return 0 self.res = 0 the DFS (n-, 0, 0, 0, 0) return self.res