1+ def conflict (state , nextX ):
2+ nextY = len (state )
3+ for i in range (nextY ):
4+ if abs (state [i ] - nextX ) in (0 , nextY - i ):
5+ return True
6+ return False
7+
8+ def queens (num , state ):
9+ for pos in range (num ):
10+ if not conflict (state , pos ):
11+ if len (state ) == num - 1 :
12+ yield (pos , )
13+ else :
14+ for result in queens (num , state + (pos ,)):
15+ yield (pos , ) + result
16+
17+ def prettyprint (solution ):
18+ def line (pos , lenght = len (solution )):
19+ return '.' * (pos ) + 'Q' + '.' * (lenght - pos - 1 )
20+ res = []
21+ for pos in solution :
22+ res .append (line (pos ))
23+
24+
25+ class Solution :
26+ def solveNQueens1 (self , n : int ) -> List [List [str ]]:
27+
28+ res = []
29+ for s in queens (num = n , state = ()):
30+ print (s )
31+ res .append (prettyprint (s ))
32+ print (len (res ))
33+ return res
34+
35+ def solveNQueens2 (self , n : int ) -> List [List [str ]]:
36+ arr = list (range (n ))
37+
38+ def _check (arr ):
39+ for i in range (0 , n ):
40+ for j in range (i + 1 , n ):
41+ if abs (i - j ) == abs (arr [i ] - arr [j ]):
42+ return False
43+ return True
44+
45+ _res = []
46+ def _dfs (pos ):
47+
48+ if pos == n - 1 :
49+ if _check (arr ):
50+ _res .append (arr [:])
51+ else :
52+ for i in range (pos , n ):
53+
54+ arr [pos ], arr [i ] = arr [i ], arr [pos ]
55+ _dfs (pos + 1 )
56+ arr [pos ], arr [i ] = arr [i ], arr [pos ]
57+
58+ _dfs (0 )
59+ res = []
60+
61+ def _replace (pos ):
62+ str_res = ['.' ]* n
63+ str_res [pos ] = 'Q'
64+ return '' .join (str_res )
65+
66+ for res_one in _res :
67+ res .append ([_replace (i ) for i in res_one ])
68+ return res
69+
70+ def solveNQueens3 (self , n : int ) -> List [List [str ]]:
71+
72+ hashtable = [False ] * (n + 1 )
73+ P = list (range (n + 1 ))
74+ res = []
75+
76+ def _replace (pos ):
77+ str_res = ['.' ]* n
78+ str_res [pos - 1 ] = 'Q'
79+ return '' .join (str_res )
80+
81+ def dfs (index ):
82+ if index == n + 1 :
83+ temp = []
84+ for i in range (1 , n + 1 ):
85+ temp .append (_replace (P [i ]))
86+ res .append (temp )
87+
88+ for x in range (1 , n + 1 ):
89+ if not hashtable [x ]:
90+ flag = True
91+ for pre in range (1 , index ):
92+ if abs (index - pre ) == abs (x - P [pre ]):
93+ flag = False
94+ break
95+
96+ if flag :
97+ P [index ] = x
98+ hashtable [x ] = True
99+ dfs (index + 1 )
100+ hashtable [x ] = False
101+ dfs (1 )
102+ return res
103+
0 commit comments