-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy pathA4.py
32 lines (26 loc) · 812 Bytes
/
A4.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
class NQueens:
def __init__(self, n):
self.n = n
self.solutions = []
def solve(self):
board = [-1] * self.n
self.place_queens(board, 0)
return self.solutions
def place_queens(self, board, row):
if row == self.n:
self.solutions.append(list(board))
return
for col in range(self.n):
if self.is_valid_move(board, row, col):
board[row] = col
self.place_queens(board, row+1)
board[row] = -1
def is_valid_move(self, board, row, col):
for i in range(row):
if board[i] == col or abs(board[i] - col) == abs(i - row):
return False
return True
n = 4
solver = NQueens(n)
solutions = solver.solve()
print(solutions)