-1

我有一个不会中断的while循环。我添加了一个冗余条件以使其中断,但这也不起作用。它应该遍历一个二维数组,看看它是否可以在那个位置放置一个特定维度的块。Block 是一个列表,而 box 是一个二维列表。这是整个程序。有问题的函数是fillBox

def makeBox(dim):
    box = [[0 for x in range(0, dim)] for y in range(0, dim)]
    return box
def printBox(lst):
    for x in lst:
        print(x)
    print()
def isSpaceFree(box, row, col, block):
    isFree = True
    if block > 1:
        if row+block-1 < len(box) and col+block-1 < len(box):
            for x in range(row,row+block):
                for y in range(col, col+block):
                    if box[x][y] != 0:
                        isFree = False
        else:
            isFree = False
    elif block == 1:
            if box[row][col] == 0:
                isFree = True
            else:
                isFree = False
    return isFree
def fillSpace(block, row, col, box):
    if block > 1:
        for x in range(row, row + block):
            for y in range(col, col + block):
                box[x][y] = block
    if block == 1:
        box[row][col] = block
    printBox(box)
def fillBox(block, box):
    row = 0
    col = 0
    while len(block) > 0:
        if len(block) == 0:
            break
        if row == len(block):
            col = 0
            row = 0
            block.pop(0)
        if col == len(block):
            col = 0
            row += 1
        if isSpaceFree(box, row, col, block[0]):
           fillSpace(block[0], row, col, box)
           block.pop(0)
            row = 0
            col = 0
            continue
        col += 1
def main():
    dim = int(input("Enter box dimension: "))
    file = open(input("Block File: "))
    blocks = []
    for x in file:
        blocks = x.split()
    for x in range(0,len(blocks)):
        blocks[x] = int(blocks[x])
    blocks.sort(reverse=True)
    box = makeBox(dim)
    fillBox(blocks, box)
    printBox(box)
main()
4

2 回答 2

1
   if row == len(block):
        col = 0
        row = 0
        block.pop(0)  # If row == 1 and len(block) == 1 This will pop the last item
    if col == len(block):
        col = 0
        row += 1
    if isSpaceFree(box, row, col, block[0]):  # Then this index will be out of bounds - correct?
于 2013-10-23T01:24:42.463 回答
1

循环中的第一个条件永远不会被触发。

如果块大于零(继续循环),则它不会立即等于零。

于 2013-10-23T00:35:49.133 回答