KatInterview

Grid Zone Coloring Feasibility

Trees & GraphsAuto-graded · 23 test cases
EasyAuto-gradedTrees & Graphstrees-graphsarraysmath-bits

Last updated

Determine whether empty grid plots can be assigned one of k colors without adjacent conflicts.

You are managing a rectangular field layout represented by a 2D matrix grid of size $m \times n$. Each cell in the matrix represents a zone:

  • 0 indicates an open plot that requires a crop assignment.
  • -1 indicates an unplantable obstacle or blocked space.

You have access to $k$ distinct crop types, represented by integers from $1$ to $k$. You must assign a crop type to every open plot (0) such that no two orthogonal (horizontally or vertically) adjacent open plots share the same crop type. Blocked spaces (-1) do not receive crops and do not create adjacency conflicts.

Write a function that determines whether a valid assignment exists for the given grid and integer $k$.

Constraints

  • $m = \text{len}(grid)$
  • $n = \text{len}(grid[0])$
  • $1 \le m, n \le 10$
  • $1 \le k \le 4$
  • grid[i][j] is either 0 or -1.

Examples

Example 1

Input: can_place_flowers([[0, 0], [0, -1]], 2)

Output: True

Example 2

Input: can_place_flowers([[0, 0], [0, 0]], 1)

Output: False

Example 3

Input: can_place_flowers([[0, -1], [-1, 0]], 1)

Output: True

Example 4

Input: can_place_flowers([[-1, -1], [-1, -1]], 1)

Output: True

Hints

Hint 1

Consider the graph formed by treating open plots (0) as nodes and orthogonal adjacencies as edges.

Hint 2

Any grid graph is bipartite. What is the chromatic number of a bipartite graph with at least one edge?

Hint 3

For k >= 2, can you always pattern the grid using alternating colors based on cell coordinates (i + j) % 2?