Fix n-queens problem (#12583)

* Fix n-queens problem

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Update n_queens.py

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Update n_queens.py

* Update n_queens.py

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: Maxim Smolskiy <mithridatus@mail.ru>
This commit is contained in:
sector 2025-02-22 16:16:29 +08:00 committed by GitHub
parent a5aed92b4c
commit 183fa06f40
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -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) >>> is_safe([[0, 0, 0], [0, 0, 0], [0, 0, 0]], 1, 1)
True 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) >>> is_safe([[1, 0, 0], [0, 0, 0], [0, 0, 0]], 1, 1)
False False
>>> is_safe([[0, 0, 1], [0, 0, 0], [0, 0, 0]], 1, 1)
False
""" """
n = len(board) # Size of the board n = len(board) # Size of the board
# Check if there is any queen in the same row, column, # Check if there is any queen in the same upper column,
# left upper diagonal, and right upper diagonal # left upper diagonal and right upper diagonal
return ( 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( 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, -1, -1))
)
and all(
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)))
) )