fork download
  1. N = 4
  2.  
  3. # Function to print the solution board
  4. def print_board(board):
  5. for row in board:
  6. print(row)
  7. print()
  8.  
  9. # Check if a queen can be safely placed at board[row][col]
  10. def is_safe(board, row, col):
  11. # Check same column
  12. for i in range(row):
  13. if board[i][col] == 1:
  14. return False
  15.  
  16. # Check upper-left diagonal
  17. i, j = row - 1, col - 1
  18. while i >= 0 and j >= 0:
  19. if board[i][j] == 1:
  20. return False
  21. i -= 1
  22. j -= 1
  23.  
  24. # Check upper-right diagonal
  25. i, j = row - 1, col + 1
  26. while i >= 0 and j < N:
  27. if board[i][j] == 1:
  28. return False
  29. i -= 1
  30. j += 1
  31.  
  32. return True
  33.  
  34. # Backtracking function to solve N-Queen
  35. def solve(board, row, solutions):
  36. # Base case: if all queens are placed (row == N), save the solution
  37. if row == N:
  38. # Save a deep copy of the board as a solution
  39. solutions.append([row[:] for row in board])
  40. return
  41.  
  42. # Try placing the queen in each column of the current row
  43. for col in range(N):
  44. if is_safe(board, row, col):
  45. board[row][col] = 1 # Place queen
  46.  
  47. # Recurse to place the queen in the next row
  48. solve(board, row + 1, solutions)
  49.  
  50. # Backtrack: remove the queen (reset to 0) before trying the next column
  51. board[row][col] = 0
  52.  
  53. # Main driver code
  54. # Initialize an empty N x N board (4x4 in this case)
  55. board = [[0] * N for _ in range(N)]
  56. solutions = []
  57. solve(board, 0, solutions)
  58.  
  59. # Print all found solutions
  60. count = 1
  61. for sol in solutions:
  62. print("Solution", count)
  63. for row in sol:
  64. print(row)
  65. print()
  66. count += 1
Success #stdin #stdout 0.08s 14176KB
stdin
4
stdout
Solution 1
[0, 1, 0, 0]
[0, 0, 0, 1]
[1, 0, 0, 0]
[0, 0, 1, 0]

Solution 2
[0, 0, 1, 0]
[1, 0, 0, 0]
[0, 0, 0, 1]
[0, 1, 0, 0]