-
Notifications
You must be signed in to change notification settings - Fork 168
/
NQueen.py
61 lines (33 loc) · 1.06 KB
/
NQueen.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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
N = 4
ld = [0] * 30
rd = [0] * 30
cl = [0] * 30
def printSolution(board):
for i in range(N):
for j in range(N):
print(board[i][j], end = " ")
print()
def solveNQUtil(board, col):
if (col >= N):
return True
for i in range(N):
if ((ld[i - col + N - 1] != 1 and
rd[i + col] != 1) and cl[i] != 1):
board[i][col] = 1
ld[i - col + N - 1] = rd[i + col] = cl[i] = 1
if (solveNQUtil(board, col + 1)):
return True
board[i][col] = 0 # BACKTRACK
ld[i - col + N - 1] = rd[i + col] = cl[i] = 0
return False
def solveNQ():
board = [[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]]
if (solveNQUtil(board, 0) == False):
printf("Solution does not exist")
return False
printSolution(board)
return True
solveNQ()