我正在尝试输入“填充正方形”的输入数,并在n×n板(列表列表)上生成这些正方形的所有可能配置。空方块表示为0,填充正方形1.例如,在具有三个实心方块的2x2网格上,可能的配置为:
[[1 1]
[1 0]]
[[1 1]
[0 1]]
[[1 0]
[1 1]]
[[0 1]
[1 1]]
每次该函数生成其中一个配置时,它都会复制它并将其附加到列表(configList)。这是我的想法(下面),但是当我开始为它编写代码时,它似乎比以前更加复杂。是否有一种更有效的方法来做一个具有x个帐篷的n×n板(实心方块代表帐篷),我将如何在python中实现它?
def findConfigs(config):
configList = []
place tents sequentially on the board
loop:
find last tent's location
for each following position on the board:
move last tent to this position
newConfig = deepcopy(config)
configList.append(newConfig)
# last tent has reached the end of the board, so-
find the previous tent
if next position is not occupied by the following tent:
move it forward
move following tents directly after
else: # the previous tent cannot move any further
find next previous tent
if next position is not occupied by the following tent...
go back to loop
return configList
答案 0 :(得分:4)
您可以使用combinations
生成0
s
>>> from itertools import combinations
>>> list(combinations(range(4), 1))
[(0,), (1,), (2,), (3,)]
只需将数字0,1,2,3映射到2x2网格上即可。
一个更大的例子可能更有说服力
>>> list(combinations(range(9), 2))
[(0, 1), (0, 2), (0, 3), (0, 4), (0, 5), (0, 6), (0, 7), (0, 8), (1, 2), (1, 3), (1, 4), (1, 5), (1, 6), (1, 7), (1, 8), (2, 3), (2, 4), (2, 5), (2, 6), (2, 7), (2, 8), (3, 4), (3, 5), (3, 6), (3, 7), (3, 8), (4, 5), (4, 6), (4, 7), (4, 8), (5, 6), (5, 7), (5, 8), (6, 7), (6, 8), (7, 8)]
这是映射到2D列表的示例
>>> from itertools import product, combinations
>>> n = 3 # 3x3
>>> m = 2 # 2 tents
>>> for i in combinations(range(n*n), m):
... print [[0 if x*n+y in i else 1 for x in range(n)] for y in range(n)]
...
[[0, 1, 1], [0, 1, 1], [1, 1, 1]]
[[0, 1, 1], [1, 1, 1], [0, 1, 1]]
[[0, 0, 1], [1, 1, 1], [1, 1, 1]]
[[0, 1, 1], [1, 0, 1], [1, 1, 1]]
[[0, 1, 1], [1, 1, 1], [1, 0, 1]]
[[0, 1, 0], [1, 1, 1], [1, 1, 1]]
[[0, 1, 1], [1, 1, 0], [1, 1, 1]]
[[0, 1, 1], [1, 1, 1], [1, 1, 0]]
[[1, 1, 1], [0, 1, 1], [0, 1, 1]]
[[1, 0, 1], [0, 1, 1], [1, 1, 1]]
[[1, 1, 1], [0, 0, 1], [1, 1, 1]]
[[1, 1, 1], [0, 1, 1], [1, 0, 1]]
[[1, 1, 0], [0, 1, 1], [1, 1, 1]]
[[1, 1, 1], [0, 1, 0], [1, 1, 1]]
[[1, 1, 1], [0, 1, 1], [1, 1, 0]]
[[1, 0, 1], [1, 1, 1], [0, 1, 1]]
[[1, 1, 1], [1, 0, 1], [0, 1, 1]]
[[1, 1, 1], [1, 1, 1], [0, 0, 1]]
[[1, 1, 0], [1, 1, 1], [0, 1, 1]]
[[1, 1, 1], [1, 1, 0], [0, 1, 1]]
[[1, 1, 1], [1, 1, 1], [0, 1, 0]]
[[1, 0, 1], [1, 0, 1], [1, 1, 1]]
[[1, 0, 1], [1, 1, 1], [1, 0, 1]]
[[1, 0, 0], [1, 1, 1], [1, 1, 1]]
[[1, 0, 1], [1, 1, 0], [1, 1, 1]]
[[1, 0, 1], [1, 1, 1], [1, 1, 0]]
[[1, 1, 1], [1, 0, 1], [1, 0, 1]]
[[1, 1, 0], [1, 0, 1], [1, 1, 1]]
[[1, 1, 1], [1, 0, 0], [1, 1, 1]]
[[1, 1, 1], [1, 0, 1], [1, 1, 0]]
[[1, 1, 0], [1, 1, 1], [1, 0, 1]]
[[1, 1, 1], [1, 1, 0], [1, 0, 1]]
[[1, 1, 1], [1, 1, 1], [1, 0, 0]]
[[1, 1, 0], [1, 1, 0], [1, 1, 1]]
[[1, 1, 0], [1, 1, 1], [1, 1, 0]]
[[1, 1, 1], [1, 1, 0], [1, 1, 0]]
答案 1 :(得分:0)
所以我认为你没有考虑旋转或反射。你可以采取另一种方法解决问题......我有多少空位?假设我们有n
。那么,我们不能通过找到所有可能的位置来实现所有可能的电路板配置,我们可以将这些n
空方块“插入”完全填充的电路板中吗?为此,我们可以使用itertools
导入,并安排所有可能的配置,特别是gnibbler指出的combinations
。