defisLineAvailable(arr, i, j, idx, idy): x, y = i, j avail = True while0 <= x < len(arr[i]) and0 <= y < len(arr[i]): if x != i and y != j and arr[x][y] == "Q": avail = False x += idx y += idy return avail
defisNodeAvailable(arr, i, j): available = True for (idx, item) inenumerate(arr[i]): if item == "Q"and idx != j: available = False for idx inrange(len(arr[i])): if idx != i and arr[idx][j] == "Q": available = False for idx, idy in [(-1, -1), (1, 1), (-1, 1), (1, -1)]: ifnot isLineAvailable(arr, i, j, idx, idy): available = False break return available
defdoRecord(arr): res = [] for line in arr: res.append("".join(line)) return res
defplaceQ(arr, i, result): if i == len(arr): result.append(doRecord(arr)) return for j inrange(len(arr)): if isNodeAvailable(arr, i, j): arr[i][j] = "Q" placeQ(arr, i + 1, result) arr[i][j] = "."
classSolution: defsolveNQueens(self, n: int) -> List[List[str]]: arr = [["."for i inrange(n)] for j inrange(n)] result = [] placeQ(arr, 0, result) return result