Greedy First-Fit Placement of Shapes on a Grid
Arrays & HashingAuto-graded · 18 test casesLast updated
Simulate placing fixed binary shapes onto a grid at the first row-major position where their filled cells hit only empty cells, labelling each by its index.
You have an empty board with rows rows and cols columns, and an ordered list of shapes. Each shape is a rectangular binary matrix: 1 marks a cell the shape occupies and 0 marks a gap that the shape does not occupy. Shapes are placed exactly as given, with no rotation and no reflection.
Process the shapes in order, starting with shapes[0]. For shape number i (0-indexed):
- Consider every possible top-left corner of the shape's rectangle on the board. The whole rectangle (including its
0cells) must lie inside the board. - Try the corners in row-major order: smaller row first, and for equal rows, smaller column first.
- A corner is valid if every
1cell of the shape lands on a board cell that is currently empty. A0cell of the shape imposes no condition, so it may sit on an already filled cell. - Take the first valid corner. Write the text
str(i + 1)into every board cell covered by a1of the shape. Each shape is placed at most once. - If no corner is valid, skip this shape and leave the board unchanged. Then continue with the next shape.
Later shapes see the effects of earlier placements. After all shapes are processed, return the board as a list of rows lists, each with cols strings. Empty cells are the string ".", and filled cells hold the label of the shape that covers them (labels can have several digits).
Implement the function that returns this final board.
Constraints
0 <= rows, cols, and the board is small enough for direct simulation.- Each shape is a non-ragged 2D list containing only
0and1. - A shape whose height exceeds
rowsor whose width exceedscolscan never be placed and is skipped. - A shape with no
1cells writes nothing, so it has no visible effect. - Labels are 1-based positions in
shapes, written as strings.
Examples
Example 1
Input: place_shapes(4, 5, [[[1, 1], [1, 0]], [[1, 1]], [[1], [1], [1]]])
Output: [['1', '1', '2', '2', '3'], ['1', '.', '.', '.', '3'], ['.', '.', '.', '.', '3'], ['.', '.', '.', '.', '.']]
Example 2
Input: place_shapes(2, 3, [[[1, 0, 1], [1, 1, 1]], [[1, 1]]])
Output: [['1', '.', '1'], ['1', '1', '1']]
Hints
Hint 1
Treat each shape independently: a nested loop over every top-left corner in row-major order, and stop at the first corner that works.
Hint 2
Only the 1-cells of the shape need to be checked against the board. 0-cells can overlap occupied cells without any problem, and they must never be written.
Hint 3
Limit the corners to rows 0..rows-height and columns 0..cols-width; a negative range means the shape is skipped automatically. Check all cells before writing any, so a failed attempt never leaves a partial placement.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This is a direct simulation. For each shape, in order, we enumerate every top-left corner at which the shape's full rectangle fits inside the board. These are rows 0..rows-h and columns 0..cols-w, where h and w are the shape's height and width. We visit corners in row-major order. At each corner we check only the 1 cells of the shape: each must land on a board cell that is still ".". The first corner that passes is used. We write the label str(i + 1) into the covered cells and stop looking at that shape. If no corner passes, the shape is skipped and the board stays as it was.
Why it is correct
- Corners are tried in row-major order and the first valid one is taken, so the chosen position is exactly the top-left-most one.
- Gaps (
0cells) are never checked and never written, so a shape can wrap around earlier pieces. - The whole check happens before any write, so a failed attempt cannot leave a partial placement.
- Because the board is updated before the next shape is handled, later shapes respect earlier placements.
- If the shape is taller or wider than the board, the corner ranges are empty and the shape is naturally skipped.
- Labels are stored as strings, so multi-digit labels are not ambiguous.
Complexity
Let h_i x w_i be the size of shape i.
- Time: O(sum over i of (rows * cols * h_i * w_i)) in the worst case, since each shape tries up to
rows * colscorners and each check scans up toh_i * w_icells, with early exit on the first conflict. - Space: O(rows * cols) for the board.
Reference solution
from typing import List
def place_shapes(rows: int, cols: int, shapes: List[List[List[int]]]) -> List[List[str]]:
board = [["." for _ in range(cols)] for _ in range(rows)]
for idx, shape in enumerate(shapes):
h = len(shape)
w = len(shape[0]) if h else 0
label = str(idx + 1)
placed = False
for top in range(rows - h + 1):
for left in range(cols - w + 1):
ok = True
for r in range(h):
for c in range(w):
if shape[r][c] == 1 and board[top + r][left + c] != ".":
ok = False
break
if not ok:
break
if ok:
for r in range(h):
for c in range(w):
if shape[r][c] == 1:
board[top + r][left + c] = label
placed = True
break
if placed:
break
return board