# work5 八皇后问题 # 在8乘8的国际象棋棋盘上,放8个皇后,皇后可以吃掉与之同行同列以及同一对角线上的其他皇后。 # 为让她们共存,找出所有放置方法。 n = 4 queens = [-1]*n used_columns = set() used_left_diagonal = set() used_right_diagonal = set() def can_put_queen(row, col): return (col not in used_columns) and (row-col not in used_right_diagonal) and (row+col not in used_left_diagonal) def put_queen(row, col): queens.append((row, col)) used_columns.add(col) used_right_diagonal.add(row-col) used_left_diagonal.add(row+col) def remove_queen(row, col): queens.remove((row, col)) used_columns.remove(col) used_right_diagonal.remove(row-col) used_left_diagonal.remove(row+col) result = list() def queen(row: int) -> list[list[str]]: if row == n: rowText = ["."] * n board = list() for i in range(n): rowText[queens[i]] = "Q" board.append("".join(rowText)) rowText[queens[i]] = "." result.append(board) for col in range(n): if not can_put_queen(row, col): continue queens[row] = col put_queen(row, col) queen(row+1) remove_queen(row, col) queen(0) for board in result: for row in board: print(row) print("------------")