-
Notifications
You must be signed in to change notification settings - Fork 0
/
N-Queen
68 lines (49 loc) · 1.16 KB
/
N-Queen
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
62
63
64
65
66
67
68
result = []
def isSafe(board, row, col):
for i in range(col):
if (board[row][i]):
return False
i = row
j = col
while i >= 0 and j >= 0:
if(board[i][j]):
return False
i -= 1
j -= 1
i = row
j = col
while j >= 0 and i < 5:
if(board[i][j]):
return False
i = i + 1
j = j - 1
return True
def solveNQUtil(board, col):
if (col == 5):
v = []
for i in board:
for j in range(len(i)):
if i[j] == 1:
v.append(j+1)
result.append(v)
return True
res = False
for i in range(5):
if (isSafe(board, i, col)):
# Place this queen in board[i][col]
board[i][col] = 1
# Make result true if any placement
# is possible
res = solveNQUtil(board, col + 1) or res
board[i][col] = 0 # BACKTRACK
return res
def solveNQ(n):
result.clear()
board = [[0 for j in range(n)]
for i in range(n)]
solveNQUtil(board, 0)
result.sort()
return result
n = 5
res = solveNQ(n)
print(res)