我正在尝试编写一个程序,可以填充一个大小为2 ** nx 2 ** n的正方形网格,其中一个正方形被三角形移除(L形块占据三个正方形)。
函数的参数是n
(电路板尺寸为2 ** n),removed_row
和removed_column
。
该板是最初都设置为0的列表列表。然后我将删除的方块设置为全局计数变量(最初为1),然后递增计数。
所以我想要的是:如果n == 2
那么在调用函数之后电路板应该是这样的:
[[4, 1, 3, 3]
[4, 4, 2, 3]
[5, 2, 2, 6]
[5, 5, 6, 6]]
其中1是移除的正方形,2至6是三聚体。
我知道如何递归地解决这个问题,我只是将它放入代码中。
基本上我想将电路板分成4个象限1,2,3和4(1指的是右上象限,4指的是右下象限)。然后放一个三角形填充每个象限的正方形,这些象限没有填充或缺少正方形。然后在每个象限上重复此过程,直到所有方块都不等于零。
这是我认为应该有效的代码,但我显然在某处出错了,因为它适用的唯一案例是n == 1
:
count = 1
def triominoes(n, removed_row=0, removed_column=0) :
global count
# initialization of the board:
board = [ [0] * 2**n for i in range(2**n) ]
# code for generating the board goes here
# you can (and are encouraged to) use recursive helper function/s
#Set the removed square to 1:
board[removed_row][removed_column] = count
count+=1
if (n==1):
for row in range(len(board)) :
for col in range(len(board[row])) :
if (board[row][col] == 0) :
board[row][col] = count
return board
#Call the helper function on each sub-board
triominoes_helper((n-1), removed_row, removed_column, 1, board) #Quadrant 1
triominoes_helper((n-1), removed_row, removed_column, 2, board) #Quadrant 2
triominoes_helper((n-1), removed_row, removed_column, 3, board) #Quadrant 3
triominoes_helper((n-1), removed_row, removed_column, 4, board) #Quadrant 4
return board
#def recursive_helper()
def triominoes_helper(n, removed_row, removed_column, location, board) :
global count
#Base Case
if (n==1):
for row in range(len(board)) :
for col in range(len(board[row])) :
if (board[row][col] == 0) :
board[row][col] = count
return board
#Recursive Case
if (location == 1) :
if (not is_removed(n, location, board)) :
board[2**(n-1)-1][2**(n-1)] = count
elif (location == 2) :
if (not is_removed(n, location, board)) :
board[2**(n-1)-1][2**(n-1)-1] = count
elif (location == 3) :
if (not is_removed(n, location, board)) :
board[2**(n-1)][2**(n-1)-1] = count
else :
if (not is_removed(n, location, board)) :
board[2**(n-1)][2**(n-1)] = count
count+=1
triominoes_helper(n-1, 2**(n-1)-1, 2**(n-1), 1, board)
triominoes_helper(n-1, 2**(n-1)-1, 2**(n-1)-1, 2, board)
triominoes_helper(n-1, 2**(n-1), 2**(n-1)-1, 3, board)
triominoes_helper(n-1, 2**(n-1), 2**(n-1), 4, board)
#Function to see if a sub-board already has a square removed
def is_removed(n, location, board) :
if (location == 1) :
for r in range(0, 2**(n-1)-1) :
for c in range(2**(n-1), 2**n-1) :
if (board[r][c] != 0) :
return True
elif (location == 2) :
for r in range(0, 2**(n-1)-1) :
print(r)
for c in range(0, 2**(n-1)-1) :
print(c)
if (board[r][c] != 0) :
return True
elif (location == 3) :
for r in range(2**(n-1), 2**n-1) :
for c in range(0, 2**(n-1)-1) :
if (board[r][c] != 0) :
return True
else :
for r in range(2**(n-1), 2**n-1) :
for c in range(2**(n-1), 2**n-1) :
if (board[r][c] != 0) :
return True
return False
print(triominoes(2))