-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNqueens.py
More file actions
69 lines (58 loc) · 1.84 KB
/
Copy pathNqueens.py
File metadata and controls
69 lines (58 loc) · 1.84 KB
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
69
import copy
class Solution:
def solveNQueens(self, n ) :
final=[]
ans=[None]*n
# row=set()
col=set()
dig=set()
def NQ(i):
if i==n:
print('ans',ans)
final.append(copy.deepcopy(ans))
return
for index in range(n):
if index not in col and (i,index) not in dig:
col.add(index)
r=i
c=index
while r<n and c<n:
dig.add((r,c))
r+=1
c+=1
r=i
c=index
while 0<=r<n and 0<=c:
dig.add((r,c))
r+=1
c-=1
ans[i]=index #important
NQ(i+1)
ans[i]=None
col.remove(index)
r=i
c=index
while r<n and c<n:
try:
dig.remove((r,c))
except:
pass
r+=1
c+=1
r=i+1
c=index-1
while 0<=r<n and 0<=c:
try:
dig.remove((r,c))
except:
pass
r+=1
c-=1
NQ(0)
order=[]
for ele in final:
ans=[['.' for _ in range(n)] for _ in range(n)]
for i in range(n):
ans[i][ele[i]]='Q'
order.append(copy.deepcopy(ans))
return order