This is Single Solutions For N-Queen and N-Queen II Problem

This is Single Solutions For N-Queen and N-Queen II Problem, Just change the return and solution is ready.

For N Queen =====> return soultions
For N Queen II =====> return no_of_solutions

Please UpVote if you like this.

class Solution:
def solveNQueens(self, n: int) -> List[List[str]]:
rows = [0] * n
hills = [0] * (2n -1)
dales = [0] * (2
n -1)

    board = [["."] * n for _ in range(n)]
    solutions = []
    
    def free_to_place_queen(row, col):
        if rows[col] or hills[row+col] or dales[row-col]:
            return False
        else :
            return True
    
    def place_queen_and_set_attack_zone(row, col):
        board[row][col] = "Q"
        rows[col] = 1
        hills[row+col] = 1
        dales[row-col] = 1
    
    def remove_queen_and_release_attacking_zone(row, col):
        board[row][col] = "."
        rows[col] = 0
        hills[row+col] = 0
        dales[row-col] = 0
        
    def backTrackNQueen(row, count):
        for col in range(n):
            if free_to_place_queen(row, col):
                place_queen_and_set_attack_zone(row,col)
                
                if row+1 == n:
                    count += 1
                    tmp = []
                    for i in range(n):
                        tmp.append(("").join(board[i]))
            
                    solutions.append(tmp)
                   
                else :
                    count = backTrackNQueen(row+1, count)
                
                remove_queen_and_release_attacking_zone(row, col)
            
        return count

    no_of_solutions = backTrackNQueen(0,0)
    return no_of_solutions
Comments (0)