八皇后问题 -- python面向对象解法
1 # 【8*8棋盘八皇后问题】 2 3 class Queen: 4 def __init__(self, row, col): 5 self.row = row 6 self.col = col 7 self.pos = (row + 1, col + 1) 8 9 def check(self, chess_board): 10 '''检查当前位置是否可放置皇后,默认每行只放一个皇后''' 11 # 检测列 12 for i in range(8): 13 if chess_board.board[i][self.col] == 0: 14 return False 15 # 检测两个斜向 16 for i in range(-7, 8): 17 if 0 <= self.row + i < 8 and 0 <= self.col + i < 8 and chess_board.board[self.row + i][self.col + i] == 0: 18 return False 19 elif 0 <= self.row + i < 8 and 0 <= self.col - i < 8 and chess_board.board[self.row + i][self.col - i] == 0: 20 return False 21 return True 22 23 24 25 class Chess_Board: 26 # 棋盘 无皇后为1,有皇后为0 27 board = [[1 for i in range(8)] for i in range(8)] 28 29 def print_board(self): 30 '''可视化打印棋盘''' 31 print('---------------------------------') 32 for i in range(8): 33 for j in range(8): 34 if self.board[i][j] == 1: 35 print(' +', end='') # + 无皇后 36 else: 37 print(' @', end='') # @ 表示皇后 38 print() 39 print('---------------------------------') 40 41 42 43 def solve(): 44 '''返回结果棋盘对象和皇后对象列表''' 45 46 def check_nextline(queens, chess_board): 47 '''已知所有皇后坐标,判断下一行是否有位置''' 48 next_col = len(queens) 49 if next_col < 8: 50 for i in range(8): 51 queen = Queen(next_col, i) 52 if queen.check(chess_board): 53 queens.append(queen) 54 chess_board.board[queen.row][queen.col] = 0 55 # chess_board.print_board() # 监控实现过程 56 return True 57 return False 58 59 60 queens = [] # 存储已放到棋盘上的皇后对象的列表 61 chess_board = Chess_Board() # 创建唯一棋盘对象 62 queen = Queen(0, 0) 63 queens.append(queen) 64 chess_board.board[queen.row][queen.col] = 0 65 while 1: 66 # 如果下一行没有位置,就将该行的皇后向右移一格 67 while not check_nextline(queens, chess_board): 68 queen = queens.pop(-1) 69 chess_board.board[queen.row][queen.col] = 1 70 while queen.col == 7: 71 queen = queens.pop(-1) 72 chess_board.board[queen.row][queen.col] = 1 73 74 queen = Queen(queen.row, queen.col + 1) 75 # 如果皇后右移后与原先皇后冲突,则继续右移 76 while not queen.check(chess_board): 77 if queen.col < 7: 78 queen = Queen(queen.row, queen.col + 1) 79 else: 80 while queen.col == 7: 81 queen = queens.pop(-1) 82 chess_board.board[queen.row][queen.col] = 1 83 84 queen = Queen(queen.row, queen.col + 1) 85 queens.append(queen) 86 chess_board.board[queen.row][queen.col] = 0 87 88 # 放满8个皇后之后跳出while 1循环 89 if len(queens) == 8: 90 break 91 return queens, chess_board 92 93 94 95 def main(): 96 '''主函数''' 97 queens, chess_board = solve() 98 for queen in queens: 99 print(queen.pos) 100 chess_board.print_board() 101 102 103 if __name__ == "__main__": 104 main()