0

我无法制作将数字放入二进制网格的函数。例如,如果给定 4 3 2 1,并且我有一个 5x5 的网格,它将如下所示...

4 4 4 4 1
4 4 4 4 0
4 4 4 4 0 
4 4 4 4 0
0 0 0 0 0 

我当前的代码读取一个文本文件并创建一个按降序排列的列表。例如,如果文本文件包含 1 2 3,它将创建一个整数列表 3 2 1。此外,我的代码会提示输入 bin #,它会创建一个 binxbin 正方形。我不知道如何将垃圾箱放入 4 号。这是应该放在我坚持的值中的函数。

def isSpaceFree(bin, row, column, block):
    if row + block > len(bin):
        return False
    if column + block > len(bin):
        return False
    if bin[row][column] == 0 :
        return True
    else:
        return False
    for r in range(row, row+block):
        if bin[row][column] != 0:
4

1 回答 1

1

如果您可以创建一个具有原点 origin和 size的正方形,而不会超出范围或重叠任何非零元素,那么听起来isSpaceFree应该返回。在这种情况下,您已经完成了 75% 的工作。您已经准备好边界检查,并且有一半的重叠检查循环。True(row, column)block

def isSpaceFree(bin, row, column, block):
    #return False if the block would go out of bounds
    if row + block > len(bin):
        return False
    if column + block > len(bin):
        return False

    #possible todo:
    #return False if row or column is negative

    #return False if the square would overlap an existing element
    for r in range(row, row+block):
        for c in range(column, column+block):
            if bin[r][c] != 0: #oops, overlap will occur
                return False

    #square is in bounds, and doesn't overlap anything. Good to go!
    return True

然后,实际放置块是相同的双嵌套循环,而是执行分配。

def place(bin, row, column, block):
    if isSpaceFree(bin, row, column, block):
        for r in range(row, row+block):
            for c in range(column, column+block):
                bin[r][c] = block

x = [
[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],
]

place(x, 0, 0, 4)

print "\n".join(str(row) for row in x)

结果:

[4, 4, 4, 4, 0]
[4, 4, 4, 4, 0]
[4, 4, 4, 4, 0]
[4, 4, 4, 4, 0]
[0, 0, 0, 0, 0]
于 2013-10-22T15:29:11.147 回答