def nqueens_problem(n:int): board = [['-']*n for i in range(n)] ans = [] def bactrack(row, cols, diagonals, anti_diagonals): #base condition if row == n: #append to solution to ans board_copy = [ ",".join(row) for row in board] ans.append(board_copy) return for col in range(n): cur_diagonal = row- col cur_antidiagonal = row+col if col in cols or cur_diagonal in diagonals or cur_antidiagonal in anti_diagonals: continue cols.add(col) diagonals.add(cur_diagonal) anti_diagonals.add(cur_antidiagonal) # place the Queen board[row][col] = 'Q' bactrack(row+1,cols,diagonals,anti_diagonals) #backtrack cols.remove(col) diagonals.remove(cur_diagonal) anti_diagonals.remove(cur_antidiagonal) board[row][col] = '-' bactrack(0,set(),set(),set()) return ans ans = nqueens_problem(5) print('*'*50) # print(ans) for val in ans: for row in val: print(row) print('*'*20)
Standard input is empty
************************************************** Q,-,-,-,- -,-,Q,-,- -,-,-,-,Q -,Q,-,-,- -,-,-,Q,- ******************** Q,-,-,-,- -,-,-,Q,- -,Q,-,-,- -,-,-,-,Q -,-,Q,-,- ******************** -,Q,-,-,- -,-,-,Q,- Q,-,-,-,- -,-,Q,-,- -,-,-,-,Q ******************** -,Q,-,-,- -,-,-,-,Q -,-,Q,-,- Q,-,-,-,- -,-,-,Q,- ******************** -,-,Q,-,- Q,-,-,-,- -,-,-,Q,- -,Q,-,-,- -,-,-,-,Q ******************** -,-,Q,-,- -,-,-,-,Q -,Q,-,-,- -,-,-,Q,- Q,-,-,-,- ******************** -,-,-,Q,- Q,-,-,-,- -,-,Q,-,- -,-,-,-,Q -,Q,-,-,- ******************** -,-,-,Q,- -,Q,-,-,- -,-,-,-,Q -,-,Q,-,- Q,-,-,-,- ******************** -,-,-,-,Q -,Q,-,-,- -,-,-,Q,- Q,-,-,-,- -,-,Q,-,- ******************** -,-,-,-,Q -,-,Q,-,- Q,-,-,-,- -,-,-,Q,- -,Q,-,-,- ********************