Skip to content

Commit

Permalink
Add solution for N-Queens II
Browse files Browse the repository at this point in the history
  • Loading branch information
Blacknahil committed Mar 4, 2024
1 parent 58e2416 commit 22ed8f1
Showing 1 changed file with 25 additions and 0 deletions.
25 changes: 25 additions & 0 deletions camp1/week3/leetcode/n-queens-ii.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
class Solution:
def totalNQueens(self, n: int) -> int:
posDiag=set()
negDiag=set()

count=0

def backtrack(row,columns):
nonlocal count
if row==n:
count+=1
return
for col in range(n):
if col in columns or (row+col) in posDiag or (row-col) in negDiag:
continue
columns.append(col)
posDiag.add(col+row)
negDiag.add(row-col)
backtrack(row+1,columns)
columns.pop()
posDiag.remove(col+row)
negDiag.remove(row-col)
backtrack(0,[])

return count

0 comments on commit 22ed8f1

Please sign in to comment.