KatInterview

Fill a Grid With Connected Crop Strips in Snake Order

Arrays & HashingAuto-graded · 21 test cases
EasyAuto-gradedArrays & Hashinggridconstructionsimulation

Last updated

Build an N by M grid in which each crop forms one edge-connected region, using a snake-order fill with a fixed, deterministic output.

A field is laid out as a grid with n rows and m columns. There are k crop types, numbered 1 to k, where k = len(counts). Crop i (1-indexed) must be planted in exactly counts[i - 1] cells. The counts add up to n * m, so every cell gets exactly one crop.

Each crop with a positive count must form a single connected region. Two cells are connected only if they share an edge (up, down, left or right). Diagonal contact does not count.

Because the result is checked automatically, your function must return one specific arrangement, built with the snake-order fill below:

  1. Visit the cells in snake order. Row 0 goes left to right, row 1 goes right to left, row 2 goes left to right, and so on.
  2. Assign crop labels along this visiting order in increasing label order. The first counts[0] visited cells get label 1, the next counts[1] cells get label 2, and so on.
  3. A crop with count 0 is skipped and does not appear in the grid.

Return the grid as a list of n rows, each a list of m integer labels, where each entry is the label at that cell's actual position (column index counted from the left).

Consecutive cells in snake order always share an edge, including where one row ends and the next begins. Every crop therefore occupies a contiguous stretch of the order and is connected.

Constraints

  • 1 <= n, 1 <= m
  • counts contains non-negative integers and sum(counts) == n * m
  • Labels are 1-indexed, so counts[0] belongs to crop 1
  • The grid may be a single row or a single column
  • Crops with count 0 do not appear in the output

Examples

Example 1

Input: fill_crop_regions(2, 3, [2, 2, 2])

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

Example 2

Input: fill_crop_regions(3, 4, [0, 5, 1, 6])

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

Example 3

Input: fill_crop_regions(1, 7, [3, 0, 4])

Output: [[1, 1, 1, 3, 3, 3, 3]]

Example 4

Input: fill_crop_regions(4, 1, [1, 0, 2, 1])

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

Hints

Hint 1

Think of the grid as one long sequence of n*m cells. First work out which crop label belongs at each position of that sequence, ignoring the 2D layout.

Hint 2

Walking the rows left-to-right, then right-to-left alternately, means the last cell of one row sits directly above or below the first cell of the next in the visiting order. That is why a contiguous run of the sequence stays connected.

Hint 3

Build the flat label list by repeating each label counts[i] times (zero counts add nothing), cut it into rows of length m, then reverse every odd-indexed row to undo the snake direction.