KatInterview

Grid Partitioning and Navigating Safe Subregions

Trees & GraphsModel answer
HardModel answerTrees & Graphstrees-graphsgridbfs

Last updated

Construct a valid contiguous layout for multiple crop zones on a grid and find the shortest path avoiding edge-touching zones.

You are given an $N \times N$ matrix grid that needs to be partitioned into $K$ distinct regions. Each region $i$ (labeled $1$ through $K$) represents a specific crop plot and must contain a designated target number of cells, given by $S_i$.

Your layout must satisfy three constraints:

  1. Every region $i$ contains exactly $S_i$ cells.
  2. Each region $i$ must form a single orthogonally connected component (a cell is connected to its north, south, east, and west neighbors).
  3. Every cell $(r, c)$ in the $N \times N$ grid must be assigned to exactly one region, meaning $\sum_{i=1}^K S_i = N^2$.

After generating your grid arrangement, you must determine the shortest Manhattan-distance path between a start cell and an end cell while avoiding any vulnerable regions.

  • A region is defined as vulnerable if at least one of its constituent cells touches the boundary of the grid (i.e., lies in row $0$, row $N-1$, column $0$, or column $N-1$).
  • A path can only step on cells belonging to non-vulnerable regions, moving 4-directionally (up, down, left, right).

Write a function design_and_navigate(N, crop_requirements, start, end) that accepts:

  • N: An integer specifying the side length of the grid ($1 \le N \le 50$).
  • crop_requirements: A list of $K$ positive integers $[S_1, S_2, \dots, S_K]$ such that $\sum S_i = N^2$.
  • start, end: Coordinates given as tuples (r, c).

The function must return:

  • A 2D list of integers of dimension $N \times N$ representing your valid grid partition (values $1$ to $K$).
  • An integer indicating the minimum path length from start to end through safe (non-vulnerable) cells. If no path exists, or if start or end themselves fall inside a vulnerable region, return -1.

Example

N = 3
crop_requirements = [4, 5]
start = (0, 0)
end = (2, 2)

# Output:
# (
#   [[1, 1, 1],
#    [2, 1, 1],
#    [2, 2, 2]],
#   -1
# )
# Explanation: Both region 1 and region 2 have cells along the border.
# Thus, no safe cells exist, and the navigation returns -1.

Hints

Hint 1

Do not use complex backtracking to construct the grid regions. Is there a deterministic traversal order that guarantees orthogonal connectivity for any arbitrary segment of cells?

Hint 2

A boustrophedon (snake-like) pattern visits all cells in a single continuous path where every consecutive pair of cells is orthogonally adjacent.

Hint 3

Once the layout is produced, identify all region labels that appear along the outer perimeter (row 0, row N-1, col 0, col N-1). Execute a standard BFS starting at `start`, treating any cell with a boundary-linked label as blocked.