[
dfs
backtracking
]
Leetcode 0051. N-Queens
Problem statement
https://leetcode.com/problems/n-queens/
Solution
This problem is similar to problem 46, basically we need to go over all n! permutations and then check if it is correct and write function to draw this solution. Let us use dfs(board, c1, c2, c3) function here, where:
boardare positions of queen for the first, second and so on lines. Length ofboardis how many queens we already used.c1is bit mask for columns,c2andc3for diagonals. Note, that we usei-j+nfor one of the diagonals to avoid negative numbers. Each time we try to take all possible positions and then check if we can put queen on this position.
Complexity
Time and space complexity is O(n!).
Code
class Solution:
def solveNQueens(self, n):
def dfs(board, i, c1, c2, c3):
if i == n: ans.append(["."*j + "Q" + "."*(n-j-1) for j in board])
for j in range(n):
if c1 & 1<<j or c2 & 1<<i-j+n or c3 & 1<<i+j: continue
dfs(board + [j], i + 1, c1 ^ 1<<j, c2 ^ 1<<i-j+n, c3 ^ 1<<i+j)
ans = []
dfs([], 0, 0, 0, 0)
return ans