Simulate dropping one piece in a Tetris-style game.
def drop_block(background: list[list[int]], block: list[list[int]], offset: int) -> list[list[int]] | None
backgroundis anH x Wgrid of0(empty) and1(filled). Row0is the top.blockis anh x wmask. Only its1cells are part of the piece;0cells are ignored completely (they may overlap filled cells, stick out of the grid, anything). The mask has at least one1.offsetis the grid column where the mask's column0lines up. The mask always fits horizontally:0 <= offsetandoffset + w <= W.
How the piece falls:
- It starts entirely above the grid: mask row
iis at grid rowi - h. - It moves down one row at a time as long as, after the move, every
1cell of the mask is either still above the grid (row< 0) or on an empty cell inside the grid (never below the last row). - When it can't move any more, it stops. If any of its
1cells is still above the grid, the piece doesn't fit: returnNone. - Otherwise write the piece into a copy of the grid (don't modify the inputs), then clear full rows: every row made only of
1s is removed, the rows above it shift down, and empty rows are added at the top so the grid staysH x W. Return the new grid.
background = [
[0, 0, 0, 0],
[0, 0, 0, 0],
[1, 0, 0, 1],
[1, 1, 0, 1],
]
block = [
[1, 1],
[0, 1],
]
drop_block(background, block, 1)
# The piece's right column slides down column 2 until its lower cell sits at row 3;
# its top row lands on row 2 (cells (2,1) and (2,2)). Rows 2 and 3 become full and are cleared:
# [[0, 0, 0, 0],
# [0, 0, 0, 0],
# [0, 0, 0, 0],
# [0, 0, 0, 0]]
drop_block([[0, 1], [0, 1]], [[1, 1]], 0)
# None: column 1 is filled at the top, so the piece can't even enter the grid
Grids are at most 200 x 200.
Show hint
Write fits(r) that checks the piece with its top mask row at grid row r (skip 0 cells, allow rows < 0, reject rows >= H and filled cells). Start at r = -h and increase r while fits(r + 1). For clearing, keep the rows that aren't all 1s and pad the top with fresh zero rows.