From 0b253baa40a7bbccdffd4dbebc0e68761a2b1626 Mon Sep 17 00:00:00 2001 From: Satyam Singh <111181853+Satyam-Singh-01@users.noreply.github.com> Date: Sun, 5 Oct 2025 01:39:22 +0530 Subject: [PATCH] Create N-Queens The n-queens puzzle is the problem of placing n queens on an n x n chessboard such that no two queens attack each other. Given an integer n, return all distinct solutions to the n-queens puzzle. You may return the answer in any order. Each solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both indicate a queen and an empty space, respectively. --- LeetCode/Problems/Python/N-Queens | 33 +++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 LeetCode/Problems/Python/N-Queens diff --git a/LeetCode/Problems/Python/N-Queens b/LeetCode/Problems/Python/N-Queens new file mode 100644 index 00000000..b6a57981 --- /dev/null +++ b/LeetCode/Problems/Python/N-Queens @@ -0,0 +1,33 @@ +class Solution: + def solveNQueens(self, n: int) -> List[List[str]]: + + if n == 0: return [] + + col = set() + diagonal = set() # determined by r+c + antidiagonal = set() # + output = [] + result = [] + + def backtrack(r): + nonlocal n,col,diagonal,antidiagonal,output,result + if r == n: + result.append(output[:]) + return + + for c in range(n): + if c in col or (r+c) in diagonal or (r-c) in antidiagonal: continue + + col.add(c) + diagonal.add(r+c) + antidiagonal.add(r-c) + output.append('.'*c + 'Q' + '.'*(n-c-1)) + backtrack(r+1) + + col.remove(c) + diagonal.remove(r+c) + antidiagonal.remove(r-c) + output.pop() + + backtrack(0) + return result