Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Missing File N-queen.py #7299

Open
HarshJainofficial opened this issue Nov 1, 2023 · 0 comments
Open

Missing File N-queen.py #7299

HarshJainofficial opened this issue Nov 1, 2023 · 0 comments

Comments

@HarshJainofficial
Copy link

class Solution:
def solveNQueens(self, n: int):
def is_safe(board, row, col):
# Check if there is a queen in the same column
for i in range(row):
if board[i][col] == 'Q':
return False

        # Check upper-left diagonal
        for i, j in zip(range(row, -1, -1), range(col, -1, -1)):
            if board[i][j] == 'Q':
                return False
        
        # Check upper-right diagonal
        for i, j in zip(range(row, -1, -1), range(col, n)):
            if board[i][j] == 'Q':
                return False
        
        return True

    def solve(board, row):
        if row == n:
            result.append(["".join(row) for row in board])
            return
        
        for col in range(n):
            if is_safe(board, row, col):
                board[row][col] = 'Q'
                solve(board, row + 1)
                board[row][col] = '.'
    
    result = []
    board = [['.' for _ in range(n)] for _ in range(n)]
    solve(board, 0)
    return result

Get user input for N

n = int(input("Enter the value of N: "))

solution = Solution()
solutions = solution.solveNQueens(n)

Display solutions

for sol in solutions:
for row in sol:
print(row)
print()

This is missing

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant