In this problem, whenever a location (x, y) is occupied, any other locations (p, q ) where p + q == x + y or p - q == x - y would be invalid. We can use this information to keep track of the indicators (xy_dif and xy_sum ) of the invalid positions and then call DFS recursively with valid positions only.
Complexity T : O(n ^ 2)
class Solution:
def solveNQueens(self, n):
"""
:type n: int
:rtype: List[List[str]]
"""
res = []
def dfs(queens, xy_dif, xy_sum):
p = len(queens)
if p == n:
res.append(queens)
for q in range(n):
if q not in queens and p - q not in xy_dif and p + q not in xy_sum:
dfs(queens + [q], xy_dif + [p - q], xy_sum + [p + q])
dfs([],[],[])
return [['.' * i + 'Q' + '.' * (n - i - 1) for i in row] for row in res]