Problem # Follow up for N-Queens problem. # # Now, instead outputting board configurations, return the total number of distinct solutions. AC class Solution(): def totalNQueens(self, n): from functools import reduce def solveNQueensRecu(solution, row, n): if row == n: solutions.append(list(map(lambda x: '.' * x + "Q" + '.' * (n - x - 1), solution))) else: for i in range(n): if i not in solution and reduce(lambda acc, j: abs(row - j) != abs(i - solution[j]) and acc, range(len(solution)), True): solveNQueensRecu(solution + [i], row + 1, n) solutions = [] solveNQueensRecu([], 0, n) return len(solutions) if __name__ == "__main__": assert Solution().totalNQueens(8) == 92