fork download
  1. def nqueens_problem(n:int):
  2.  
  3. board = [['-']*n for i in range(n)]
  4. ans = []
  5.  
  6. def bactrack(row, cols, diagonals, anti_diagonals):
  7. #base condition
  8. if row == n:
  9. #append to solution to ans
  10. board_copy = [ ",".join(row) for row in board]
  11. ans.append(board_copy)
  12. return
  13.  
  14.  
  15. for col in range(n):
  16. cur_diagonal = row- col
  17. cur_antidiagonal = row+col
  18.  
  19. if col in cols or cur_diagonal in diagonals or cur_antidiagonal in anti_diagonals:
  20. continue
  21.  
  22. cols.add(col)
  23. diagonals.add(cur_diagonal)
  24. anti_diagonals.add(cur_antidiagonal)
  25. # place the Queen
  26. board[row][col] = 'Q'
  27. bactrack(row+1,cols,diagonals,anti_diagonals)
  28. #backtrack
  29. cols.remove(col)
  30. diagonals.remove(cur_diagonal)
  31. anti_diagonals.remove(cur_antidiagonal)
  32. board[row][col] = '-'
  33.  
  34.  
  35. bactrack(0,set(),set(),set())
  36. return ans
  37.  
  38. ans = nqueens_problem(5)
  39. print('*'*50)
  40.  
  41. # print(ans)
  42.  
  43. for val in ans:
  44. for row in val:
  45. print(row)
  46. print('*'*20)
Success #stdin #stdout 0.03s 9712KB
stdin
Standard input is empty
stdout
**************************************************
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,-,-,-
********************