Skip to content

Fix n-queens problem #12583

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

Merged
merged 6 commits into from
Feb 22, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 13 additions & 6 deletions backtracking/n_queens.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,21 +27,28 @@ def is_safe(board: list[list[int]], row: int, column: int) -> bool:

>>> is_safe([[0, 0, 0], [0, 0, 0], [0, 0, 0]], 1, 1)
True
>>> is_safe([[0, 1, 0], [0, 0, 0], [0, 0, 0]], 1, 1)
False
>>> is_safe([[1, 0, 0], [0, 0, 0], [0, 0, 0]], 1, 1)
False
>>> is_safe([[0, 0, 1], [0, 0, 0], [0, 0, 0]], 1, 1)
False
"""

n = len(board) # Size of the board

# Check if there is any queen in the same row, column,
# left upper diagonal, and right upper diagonal
# Check if there is any queen in the same upper column,
# left upper diagonal and right upper diagonal
return (
all(board[i][j] != 1 for i, j in zip(range(row, -1, -1), range(column, n)))
all(board[i][j] != 1 for i, j in zip(range(row), [column] * row))
and all(
board[i][j] != 1
for i, j in zip(range(row - 1, -1, -1), range(column - 1, -1, -1))
)
and all(
board[i][j] != 1 for i, j in zip(range(row, -1, -1), range(column, -1, -1))
board[i][j] != 1
for i, j in zip(range(row - 1, -1, -1), range(column + 1, n))
)
and all(board[i][j] != 1 for i, j in zip(range(row, n), range(column, n)))
and all(board[i][j] != 1 for i, j in zip(range(row, n), range(column, -1, -1)))
)


Expand Down