The n-queens puzzle is the problem of placing n queens on an n x n chessboard such that no two queens attack each other.
Given an integer n, return all distinct solutions to the n-queens puzzle. You may return the answer in any order.
Each solution contains a distinct board configuration of the n-queens’ placement, where ‘Q’ and ‘.’ both indicate a queen and an empty space, respectively.
Example 1:
Input: n = 4 Output: [[“.Q..”,”…Q”,”Q…”,”..Q.”],[“..Q.”,”Q…”,”…Q”,”.Q..”]] Explanation: There exist two distinct solutions to the 4-queens puzzle as shown above
defdfs(self, n, start, path, res, col_set, diag_set, anti_diag_set): if start == n: # remember not len(path) res.append(list(path)) return for i inrange(n): # 4 ifnotself.is_valid(start, i, col_set, diag_set, anti_diag_set): continue path.append(i) # [0, 2] col_set.add(i) diag_set.add(start - i) anti_diag_set.add(start + i) self.dfs(n, start + 1, path, res, col_set, diag_set, anti_diag_set) anti_diag_set.remove(start + i) diag_set.remove(start - i) col_set.remove(i) path.pop()
defis_valid(self, i, val, col_set, diag_set, anti_diag_set): if val in col_set or i - val in diag_set or i + val in anti_diag_set: returnFalse returnTrue
defverticalOrder2(self, root: TreeNode) -> List[List[int]]: idx_to_list, res = collections.defaultdict(list), [] self.dfs(root, 0, 0, idx_to_list) sorted_keys = sorted(list(idx_to_list.keys())) for i in sorted_keys: li = sorted(idx_to_list[i]) res.append([node[2] for node in li]) return res