-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathn_queen.py
More file actions
44 lines (38 loc) · 940 Bytes
/
n_queen.py
File metadata and controls
44 lines (38 loc) · 940 Bytes
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
def isValid(grid,x,y,n):
rowCheck = all([grid[x][j] != 1 for j in range(n)])
colCheck = all([grid[j][y] != 1 for j in range(n)])
if not rowCheck or not colCheck:
return False
i = x+1
j = y+1
while(i<n and j<n):
if grid[i][j] != 1:
i += 1
j += 1
else:
return False
i = x-1
j = y-1
while(i>=0 and j>=0):
if grid[i][j] != 1:
i -= 1
j -= 1
else:
return False
return True
def Queen(grid,row,n):
for i in range(0,n):
if isValid(grid,row,i,n):
grid[row][i] = 1
if row==n-1:
return True
result = Queen(grid,row+1)
if result:
return True
grid[row][i] = 0
return False
grid = []
for i in range(n):
grid.append([0]*n)
if Queen(grid,0,n):
print(grid)