存在包含0或1的amxn矩阵。定义2x2的正方形子矩阵,其仅包含0.如果从原始矩阵切割出这样的正方形子矩阵,则我们必须找出这样的正方形子矩阵的最大数量可以从原始矩阵切割。严格切割意味着没有2平方子矩阵可以重叠。 对于前 - 这是一个5x5矩阵
0 0 0 1 0
0 0 0 0 0
1 0 0 0 0
0 0 0 1 0
0 0 0 0 0
如果我们从(0,0)开始切割2x2的正方形子矩阵,那么剩下的矩阵
0 1 0
0 0 0
1 0 0 0 0
0 0 0 1 0
0 0 0 0 0
可以切割更多2x2平方子矩阵 在这个给定输入中,最多可以切割3个这样的矩阵。如果我用'a'标记它们
a a 0 1 0
a a a a 0
1 0 a a 0
a a 0 1 0
a a 0 0 0
我尝试过回溯/递归方法,但它只适用于较小尺寸的输入。任何人都可以提出更有效的方法吗?
编辑:我用“a”标记矩阵元素,表明这是一个可以剪切的子矩阵。我们只需报告可从该矩阵中获得的最大2x2子矩阵(包含全0)
答案 0 :(得分:0)
为了完整起见,我改变了脚本来做一些粗略的递归,你是对的很难不采用递归的方式来做...
这个想法:
f(matrix,count)
IF count > length THEN
length = count
add all options to L
IF L is empty THEN
return
FOR each option in L
FOR each position in option
set position in matrix to 1
f(matrix,count+1)
FOR each position in option
set position in matrix to 0
where options are all 2x2 submatrices with only 0s that are currently in matrix
length = 0
set M to the matrix with 1s and 0s
f(M,0)
在python中:
import copy
def possibilities(y):
l = len(y[0]) # horizontal length of matrix
h = len(y) # verticle length of matrix
sub = 2 # length of square submatrix you want to shift in this case 2x2
length = l-sub+1
hieght = h-sub+1
x = [[0,0],[0,1],
[1,0],[1,1]]
# add all 2x2 to list L
L=[]
for i in range(hieght):
for j in range(length):
if y[x[0][0]][x[0][1]]==0 and y[x[1][0]][x[1][1]]==0 and y[x[2][0]][x[2][1]]==0 and y[x[3][0]][x[3][1]]==0:
# create a copy of x
c = copy.deepcopy(x)
L.append(c)
for k in x: # shift submatrix to the right 1
k[1]+=1
(x[0][1],x[1][1],x[2][1],x[3][1]) = (0,1,0,1)
for k in x: # shift submatrix down 1
k[0]+=1
return L
def f(matrix,count):
global length
if count > length:
length = count
L = possibilities(matrix)
if not L:
return
for option in L:
for position in option:
matrix[position[0]][position[1]]=1
f(matrix,count+1)
# reset back to 0
for position in option:
matrix[position[0]][position[1]]=0
length = 0
# matrix
M = [[0,0,1,0,0,0],
[0,0,0,0,0,0],
[1,1,0,0,0,0],
[0,1,1,0,0,0]]
f(M,0)
print(length)