【发布时间】:2022-01-05 21:29:33
【问题描述】:
我需要一些帮助来找到可以解决以下问题的算法。
给定二维板和行/列的目标值,行/列的总和应等于这些目标值。可以通过将board value设置为0来实现。
就我而言,我有以下板:
board = [
[5,9,4,6,1],
[6,2,3,6,7],
[3,4,8,4,4],
[2,2,6,4,6],
[7,3,1,6,5]
]
[24,13,15,8,12] 行具有以下值,[8,11,13,18,22] 列具有以下值。
因此,棋盘应如下所示:
board = [
[5,9,4,6,0],
[0,0,0,6,7],
[3,0,8,0,4],
[0,2,0,0,6],
[0,0,1,6,5]
]
目前,我的代码如下所示:
# chooses a next cell
def choose_cell(x,y,visited):
for i in range(x,board_len):
for j in range(y, board_len):
if visited[i][j] == 0 and is_cell_valid(i,j):# if the cell is not visited and is valid => return i,j
return i,j
for i in range(0,board_len):
for j in range(0, board_len):
if visited[i][j] == 0 and is_cell_valid(i,j):
return i,j
return -1,-1
# checks if x,y are not out of board range
def is_cell_valid(x_coord, y_coord):
if (x_coord < 0 or y_coord < 0) or (x_coord >= board_len or y_coord >= board_len):
return False
return True
def solve_board(x, y, visited):
# if the sum of the row/column equals target row/column value => returns True
if row_sum() == row_goal and col_sum() == col_goal:
return True
if x == -1:# if -1 is returned it means that the algorithm reached the end of a board
return False
x,y=choose_cell(x,y, visited)
# mark the current board element as visited
visited[x][y] = 1
# save current board element for future use, put 0 in the board instead
temp = board[x][y]
board[x][y] = 0
# that's where my mind goes blank
if solve_board(x,y,visited) == False:
board[x][y] = temp
if solve_board(x,y,visited):
return True
return False
我尝试在这里实现以下内容:
- 选择一个单元格。
- 将该值设置为零。
- 递归并尝试求解棋盘。
- 如果棋盘未解,则回溯并将棋盘元素设置为之前的值。递归地尝试求解该值的棋盘。
- 如果棋盘已解,则返回 True。
【问题讨论】:
标签: python recursion multidimensional-array grid