It sounds like isSpaceFree
should return True
if you can create a square with origin origin (row, column)
and size block
, without going out of bounds or overlapping any non-zero elements. In which case, you're 75% of the way there. You have the bounds checking ready, and half of the overlap check loop.
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
Then, actually placing the block is the same double-nested loop, but instead performing an assignment.
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)
Result:
[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]