KatInterview

Fewest Presses to Morph One Light Grid Into Another

Math & Bit ManipulationAuto-graded · 19 test cases
HardAuto-gradedMath & Bit Manipulationgaussian-eliminationgf2bitmask

Last updated

Find the smallest set of cell presses that turns one on/off grid into another, where each press flips a cell and its neighbours. Tests GF(2) elimination and null-space minimisation.

You are given two rectangular grids of the same size, start and goal. Each cell holds 0 (off) or 1 (on).

Pressing a cell flips that cell and its up, down, left and right neighbours. Neighbours outside the grid are ignored. Presses can be done in any order, and the final state depends only on how many times each cell is pressed.

Find a smallest set of cells to press so that start becomes goal.

Output

  • If no sequence of presses transforms start into goal, return None.
  • If either dimension of the grid is zero (empty grid), return [].
  • Otherwise return a list of [row, col] pairs (0-indexed), one per pressed cell. No cell appears twice, since pressing a cell twice cancels out.

Tie-breaking

Several minimum-size answers may exist. Return the one that is smallest in lexicographic order when its cells are listed in row-major order, i.e. sorted by row, then by col. Compare two answers pair by pair, and compare each pair by row first, then column. All minimum-size answers have the same length, so this comparison is well defined.

If start equals goal, the answer is [].

Constraints

  • 0 <= m, n <= 10, where m is the number of rows and n the number of columns.
  • Both grids have identical dimensions and are rectangular.
  • Every entry is 0 or 1.
  • The returned list must be in row-major order.

Examples

Example 1

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

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

Example 2

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

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

Example 3

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

Output: [[0, 0]]

Hints

Hint 1

Pressing a cell twice cancels out and the order does not matter, so each cell is either pressed (1) or not (0). Write one parity equation per cell: the XOR of the presses in its plus-shaped neighbourhood equals start XOR goal at that cell.

Hint 2

Solve the m*n by m*n system over GF(2) with Gauss-Jordan elimination, storing each row as a Python integer so a row operation is a single XOR. A row with no coefficients but right-hand side 1 means no solution.

Hint 3

All solutions form a particular solution XOR any combination of null-space basis vectors, and the null space has dimension at most min(m, n) <= 10. Enumerate all combinations (a Gray code makes each step one XOR), keep the smallest popcount, and break ties by the lexicographically smallest row-major list.