-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path51_N-Queens.py
60 lines (58 loc) · 1.92 KB
/
51_N-Queens.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
class Solution(object):
def iteration(self,n,num,rows,cols,final_rows,final_cols):
"""
:type n: int
:rtype: List[List[str]]
"""
search_fail = 1
for i in range(n):
if(i in cols):
pass
else:
temp_flag = 1
for j in range(len(rows)):
if(abs(num-rows[j]) == abs(i-cols[j])):
temp_flag = 0
else:
pass
if(temp_flag):
search_fail = 0
rows.append(num)
cols.append(i)
if(n-1-num == 0):
final_rows.append(rows)
final_cols.append(cols)
else:
fail_flag,final_rows, final_cols = self.iteration(n,num+1,rows,cols,final_rows,final_cols)
if(fail_flag):
rows = rows[:-1]
cols = cols[:-1]
else:
pass
else:
pass
return search_fail,final_rows,final_cols
def solveNQueens(self,n):
"""
:type n: int
:rtype: List[List[str]]
"""
chess = []
if(n == 1):
chess.append(['Q'])
rows = []
cols = []
final_rows = []
final_cols = []
for i in range(n):
rows = [0]
cols = [i]
fail_flag,final_rows,final_cols = self.iteration(n,1,rows,cols,final_rows,final_cols)
for i in range(len(final_rows)):
chess_temp = []
for j in range(n):
temp = ['.' for x in range(n)]
temp[final_cols[i][j]] = 'Q'
chess_temp.append(''.join(temp))
chess.append(chess_temp)
return chess