-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy path51.py
30 lines (29 loc) · 1.04 KB
/
51.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
# https://neetcode.io/problems/n-queens
# https://leetcode.com/problems/n-queens/
from typing import List
class Solution:
def solveNQueens(self, n: int) -> List[List[str]]:
res = []
posDiag, negDiag, col = set(), set(), set()
queens = set()
def dfs(r):
if r == n:
res.append([])
for r in range(n):
row = []
for c in range(n):
row.append('Q' if (r, c) in queens else '.')
res[-1].append("".join(row))
for c in range(n):
if r + c not in posDiag and r - c not in negDiag and c not in col:
queens.add((r, c))
posDiag.add(r + c)
negDiag.add(r - c)
col.add(c)
dfs(r + 1)
queens.remove((r, c))
posDiag.remove(r + c)
negDiag.remove(r - c)
col.remove(c)
dfs(0)
return res