Retranslate the complete English edition from Simplified Chinese (#2010)

* Retranslate the complete English edition from Simplified Chinese

* Polish three English explanations after reader-focused review
This commit is contained in:
Yudong Jin
2026-10-31 03:35:51 +08:00
committed by GitHub
parent ef46e2ed95
commit 14c314c08c
1502 changed files with 29459 additions and 23517 deletions

View File

@@ -14,48 +14,48 @@ def backtrack(
diags1: list[bool],
diags2: list[bool],
):
"""Backtracking algorithm: N queens"""
# When all rows are placed, record the solution
"""Backtracking: n-queens"""
# Record a solution when a queen has been placed in every row
if row == n:
res.append([list(row) for row in state])
return
# Traverse all columns
# Iterate over all columns
for col in range(n):
# Calculate the main diagonal and anti-diagonal corresponding to this cell
# Calculate the main-diagonal and anti-diagonal indices for this square
diag1 = row - col + n - 1
diag2 = row + col
# Pruning: do not allow queens to exist in the column, main diagonal, and anti-diagonal of this cell
# Prune: the square must have no queen in its column, main diagonal, or anti-diagonal
if not cols[col] and not diags1[diag1] and not diags2[diag2]:
# Attempt: place the queen in this cell
# Try: place a queen on this square
state[row][col] = "Q"
cols[col] = diags1[diag1] = diags2[diag2] = True
# Place the next row
# Place a queen in the next row
backtrack(row + 1, n, state, res, cols, diags1, diags2)
# Backtrack: restore this cell to an empty cell
# Backtrack: restore this square to empty
state[row][col] = "#"
cols[col] = diags1[diag1] = diags2[diag2] = False
def n_queens(n: int) -> list[list[list[str]]]:
"""Solve N queens"""
# Initialize an n*n chessboard, where 'Q' represents a queen and '#' represents an empty cell
"""Solve the n-queens problem"""
# Initialize an n*n board, where 'Q' represents a queen and '#' represents an empty square
state = [["#" for _ in range(n)] for _ in range(n)]
cols = [False] * n # Record whether there is a queen in the column
diags1 = [False] * (2 * n - 1) # Record whether there is a queen on the main diagonal
diags2 = [False] * (2 * n - 1) # Record whether there is a queen on the anti-diagonal
cols = [False] * n # Track whether a column contains a queen
diags1 = [False] * (2 * n - 1) # Track whether a main diagonal contains a queen
diags2 = [False] * (2 * n - 1) # Track whether an anti-diagonal contains a queen
res = []
backtrack(0, n, state, res, cols, diags1, diags2)
return res
"""Driver Code"""
"""Driver code"""
if __name__ == "__main__":
n = 4
res = n_queens(n)
print(f"Input chessboard size is {n}")
print(f"There are {len(res)} queen placement solutions")
print(f"The input board has width and height {n}")
print(f"Number of ways to place the queens: {len(res)}")
for state in res:
print("--------------------")
for row in state: