Skip to content

Commit 631a3ce

Browse files
committed
Simplify is_safe code
1 parent a1853d6 commit 631a3ce

File tree

1 file changed

+11
-22
lines changed

1 file changed

+11
-22
lines changed

Diff for: backtracking/n_queens.py

+11-22
Original file line numberDiff line numberDiff line change
@@ -26,32 +26,21 @@ def is_safe(board: list[list[int]], row: int, column: int) -> bool:
2626
Boolean Value
2727
2828
"""
29-
30-
n = len(board) # Size of the board
31-
32-
# Check if there is any queen in the same row
33-
for i in range(n):
34-
if board[row][i] == 1:
35-
return False
36-
# Check if there is any queen in the same column
37-
for i in range(n):
38-
if board[i][column] == 1:
39-
return False
40-
# Check if there is any queen in the left upper diagonal
41-
for i, j in zip(range(row, -1, -1), range(column, -1, -1)):
42-
if board[i][j] == 1:
43-
return False
44-
# Check if there is any queen in the right upper diagonal
45-
for i, j in zip(range(row, -1, -1), range(column, n)):
46-
if board[i][j] == 1:
47-
return False
48-
return True
29+
30+
n = len(board) # Size of the board
31+
32+
# Check if there is any queen in the same row, column,
33+
# left upper diagonal, and right upper diagonal
34+
return all(board[i][j] != 1 for i, j in zip(range(row, -1, -1), range(column, n))) \
35+
and all(board[i][j] != 1 for i, j in zip(range(row, -1, -1), range(column, -1, -1))) \
36+
and all(board[i][j] != 1 for i, j in zip(range(row, n), range(column, n))) \
37+
and all(board[i][j] != 1 for i, j in zip(range(row, n), range(column, -1, -1)))
4938

5039

5140
def solve(board: list[list[int]], row: int) -> bool:
5241
"""
53-
This function creates a state space tree and calls the safe function until it receives a
54-
False Boolean and terminates that branch and backtracks to the next
42+
This function creates a state space tree and calls the safe function until it
43+
receives a False Boolean and terminates that branch and backtracks to the next
5544
possible solution branch.
5645
"""
5746
if row >= len(board):

0 commit comments

Comments
 (0)