Skip to content
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
Fix n-queens problem (TheAlgorithms#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>
  • Loading branch information
3 people authored Feb 22, 2025
commit 183fa06f40e80c6e86ceda6e7c7d23eaf91507ac
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