-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy pathn-queens.py
51 lines (37 loc) · 1.32 KB
/
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
from typing import List
class Solution(object):
@staticmethod
def solveNQueens(n):
currRes = []
res = []
def backtrack(row, colSet, diagSet, antiDiagSet):
# moved past the grid, we could place all
if row == n:
acc = []
for r in currRes:
string = ['.'] * n
string[r] = 'Q'
acc.append(''.join(string))
res.append(acc)
return
for col in range(n):
diag = row - col
antiDiag = row + col
if (col in colSet) or (diag in diagSet) or (antiDiag in antiDiagSet):
continue
currRes.append(col)
colSet.add(col)
diagSet.add(diag)
antiDiagSet.add(antiDiag)
backtrack(row + 1, colSet, diagSet, antiDiagSet)
currRes.pop()
colSet.remove(col)
diagSet.remove(diag)
antiDiagSet.remove(antiDiag)
backtrack(0, set(), set(), set())
return res
# Checking in console
if __name__ == '__main__':
Instant = Solution()
Solve = Instant.solveNQueens(n=4) # n = 4 -> [[".Q..","...Q","Q...","..Q."],["..Q.","Q...","...Q",".Q.."]]
print(Solve)