Advertisement
amu2002

nqueens

Nov 20th, 2023
38
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.92 KB | None | 0 0
  1. class NQueensProblem:
  2.     def __init__(self, n):
  3.         self.queens = [-1] * n
  4.         self.numSolutions = 0
  5.         self.found_solution = False  
  6.  
  7.     def solve(self):
  8.         self.solve_helper(0)
  9.  
  10.     def solve_helper(self, row):
  11.         if row == len(self.queens):
  12.             if not self.found_solution:  
  13.                 self.numSolutions += 1
  14.                 self.print_solution()
  15.                 self.found_solution = True  
  16.         else:
  17.             for col in range(len(self.queens)):
  18.                 self.queens[row] = col
  19.                 if self.is_valid(row):
  20.                     self.solve_helper(row + 1)
  21.  
  22.     def is_valid(self, row):
  23.         for i in range(row):
  24.             if (
  25.                 self.queens[i] == self.queens[row]
  26.                 or abs(self.queens[i] - self.queens[row]) == row - i
  27.             ):
  28.                 return False
  29.         return True
  30.  
  31.     def print_solution(self):
  32.         if self.numSolutions == 1:
  33.             print("Solution:", end=" ")
  34.         for i in range(len(self.queens)):
  35.             print(self.queens[i], end=" ")
  36.         print()
  37.         print("The Matrix Representation:")
  38.         for i in range(len(self.queens)):
  39.             for j in range(len(self.queens)):
  40.                 if j == self.queens[i]:
  41.                     print("1", end=" ")  
  42.                 else:
  43.                     print("0", end=" ")  
  44.             print()
  45.         print()
  46.  
  47. if __name__ == "__main__":
  48.     n = int(input("Enter N for the N-Queens problem: "))
  49.     NQueensProblem = NQueensProblem(n)
  50.     NQueensProblem.solve()
  51.  
  52. """
  53. Enter N for the N-Queens problem: 4
  54. Solution: 1 3 0 2
  55. The Matrix Representation:
  56. 0 1 0 0
  57. 0 0 0 1
  58. 1 0 0 0
  59. 0 0 1 0
  60.  
  61. Enter N for the N-Queens problem: 8
  62. Solution: 0 4 7 5 2 6 1 3
  63. The Matrix Representation:
  64. 1 0 0 0 0 0 0 0
  65. 0 0 0 0 1 0 0 0
  66. 0 0 0 0 0 0 0 1
  67. 0 0 0 0 0 1 0 0
  68. 0 0 1 0 0 0 0 0
  69. 0 0 0 0 0 0 1 0
  70. 0 1 0 0 0 0 0 0
  71. 0 0 0 1 0 0 0 0
  72. """
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement