非递归实现Python 8×8棋盘八皇后问题的空行异常调试求助
迭代版八皇后实现空行异常问题
我基于Python实现8×8棋盘下的八皇后问题,运行代码后始终输出包含2个全零空行的结果。
错误输出示例:
[1, 0, 0, 0, 0, 0, 0, 0] [0, 0, 1, 0, 0, 0, 0, 0] [0, 0, 0, 0, 1, 0, 0, 0] [0, 1, 0, 0, 0, 0, 0, 0] [0, 0, 0, 0, 0, 0, 0, 0] [0, 0, 0, 0, 0, 0, 0, 0] [0, 0, 0, 1, 0, 0, 0, 0] [0, 0, 0, 0, 0, 0, 1, 0]
理想合规输出的目标皇后放置位置为:
board[4][5] = 1board[5][7] = 1
相关实现要求:
- 刻意未采用递归方式实现求解函数
- 需通过现有迭代逻辑完成求解,定位代码存在的缺陷
完整Python实现代码:
def checksquares(board, row, column): rowtemp = row columntemp = column for i in range(0,8): if board[i][column] == 1: return False for j in range(0,8): if board[row][j] == 1: return False while rowtemp > 0 and columntemp > 0: rowtemp = rowtemp - 1 columntemp = columntemp - 1 while rowtemp < 7 and columntemp < 7: if board[rowtemp][columntemp] == 1: return False rowtemp = rowtemp + 1 columntemp = columntemp + 1 rowtemp = row columntemp = column while rowtemp > 0 and columntemp < 7: rowtemp = rowtemp - 1 columntemp = columntemp + 1 while rowtemp < 7 and columntemp > 0: if board[rowtemp][columntemp] == 1: return False rowtemp = rowtemp + 1 columntemp = columntemp - 1 return True def placequeens(board, queencount): temp = [0,0,0,0,0,0,0,0] for i in range(0,8): for j in range(temp[i],8): if checksquares(board, i, j) == True: board[i][j] = 1 queencount = queencount + 1 temp[i] = j if board[i] == [0,0,0,0,0,0,0,0]: board[i - 1] = [0,0,0,0,0,0,0,0] if temp[i - 1] < 7: temp[i - 1] = temp[i - 1] + 1 elif temp[i - 1] == 7: temp[i - 1] = 7 temp[i] = 0 board = [ [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0] ] queencount = 0 placequeens(board, queencount) print(board)
内容的提问来源于stack exchange,提问作者Tofu
相关产品推荐
相关产品推荐

