Skip to content

Commit 183fa06

Browse files
infrablue1pre-commit-ci[bot]MaximSmolskiy
authored
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 <[email protected]>
1 parent a5aed92 commit 183fa06

File tree

1 file changed

+13
-6
lines changed

1 file changed

+13
-6
lines changed

Diff for: backtracking/n_queens.py

+13-6
Original file line numberDiff line numberDiff line change
@@ -27,21 +27,28 @@ def is_safe(board: list[list[int]], row: int, column: int) -> bool:
2727
2828
>>> is_safe([[0, 0, 0], [0, 0, 0], [0, 0, 0]], 1, 1)
2929
True
30+
>>> is_safe([[0, 1, 0], [0, 0, 0], [0, 0, 0]], 1, 1)
31+
False
3032
>>> is_safe([[1, 0, 0], [0, 0, 0], [0, 0, 0]], 1, 1)
3133
False
34+
>>> is_safe([[0, 0, 1], [0, 0, 0], [0, 0, 0]], 1, 1)
35+
False
3236
"""
3337

3438
n = len(board) # Size of the board
3539

36-
# Check if there is any queen in the same row, column,
37-
# left upper diagonal, and right upper diagonal
40+
# Check if there is any queen in the same upper column,
41+
# left upper diagonal and right upper diagonal
3842
return (
39-
all(board[i][j] != 1 for i, j in zip(range(row, -1, -1), range(column, n)))
43+
all(board[i][j] != 1 for i, j in zip(range(row), [column] * row))
44+
and all(
45+
board[i][j] != 1
46+
for i, j in zip(range(row - 1, -1, -1), range(column - 1, -1, -1))
47+
)
4048
and all(
41-
board[i][j] != 1 for i, j in zip(range(row, -1, -1), range(column, -1, -1))
49+
board[i][j] != 1
50+
for i, j in zip(range(row - 1, -1, -1), range(column + 1, n))
4251
)
43-
and all(board[i][j] != 1 for i, j in zip(range(row, n), range(column, n)))
44-
and all(board[i][j] != 1 for i, j in zip(range(row, n), range(column, -1, -1)))
4552
)
4653

4754

0 commit comments

Comments
 (0)