KatInterview

Sequential Shape Placement on a Matrix

Arrays & HashingAuto-graded · 21 test cases
MediumAuto-gradedArrays & Hashingmatrixsimulationgreedy

Last updated

Tests matrix manipulation, collision detection, and ordered simulation by placing fixed shapes onto a grid.

You are given two positive integers n and m representing the dimensions of a grid, and a list figures containing shape identifiers. Each identifier is one of "A", "B", "C", "D", or "E".

Your task is to build an n × m matrix that starts filled with zeros. You will then place each shape from figures onto this matrix in the order given.

Each shape is defined by a pattern where 1 indicates an occupied cell and 0 indicates an empty cell:

  • Shape A: [[1]] (a single cell)
  • Shape B: [[1, 1, 1]] (a horizontal bar of length 3)
  • Shape C: [[1, 1], [1, 1]] (a 2×2 square)
  • Shape D: [[1, 0], [1, 1], [1, 0]] (a vertical T-shape)
  • Shape E: [[0, 1, 0], [1, 1, 1]] (an inverted T-shape)

For each shape in sequence (using zero-based indexing i):

  1. Scan all possible positions in the grid from top to bottom, left to right (position (r, c) represents where the shape's top-left corner would be placed).
  2. A position is valid only if:
    • Every cell marked 1 in the shape stays within the grid boundaries.
    • Every cell marked 1 in the shape overlaps only grid cells that currently contain 0.
  3. Place the shape at the first valid position found. Mark each cell occupied by a 1 in the shape with the value i + 1.
  4. If no valid position exists for a shape, skip it entirely (the grid remains unchanged for that shape).

Shapes cannot be rotated or flipped. Cells marked 0 in a shape pattern are ignored and do not affect placement.

Return the final matrix after processing all shapes.

Constraints

  • 1 ≤ n, m ≤ 100
  • 0 ≤ len(figures) ≤ 1000
  • Each element in figures is one of "A", "B", "C", "D", "E"

Examples

Example 1

Input: sequential_shape_placement(4, 5, ['A', 'B', 'C', 'D', 'E'])

Output: [[1, 2, 2, 2, 0], [3, 3, 4, 0, 0], [3, 3, 4, 4, 0], [0, 0, 4, 0, 0]]

Example 2

Input: sequential_shape_placement(2, 3, ['E', 'A', 'B'])

Output: [[2, 1, 0], [1, 1, 1]]

Example 3

Input: sequential_shape_placement(3, 4, ['D', 'D', 'D'])

Output: [[1, 0, 2, 0], [1, 1, 2, 2], [1, 0, 2, 0]]

Hints

Hint 1

Scan positions in row-major order: iterate rows first, then columns within each row.

Hint 2

A shape can be placed even if its empty cells (marked 0) overlap filled grid cells—only the occupied cells (marked 1) matter.

Hint 3

Each shape receives a label equal to its index plus one, regardless of whether earlier shapes were skipped.