Fewest Presses to Morph One Light Grid Into Another
Math & Bit ManipulationAuto-graded · 19 test casesLast 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
startintogoal, returnNone. - 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, wheremis the number of rows andnthe number of columns.- Both grids have identical dimensions and are rectangular.
- Every entry is
0or1. - 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.
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Pressing a cell twice does nothing and presses commute, so a plan is just a 0/1 choice per cell. Let x[i][j] be 1 if cell (i, j) is pressed.
A cell ends up in its goal state exactly when the number of presses in its plus-shaped neighbourhood (itself and its in-grid neighbours) has the same parity as start XOR goal at that cell. This gives one equation per cell over GF(2), where addition is XOR: A x = b, with N = m*n unknowns.
- Build the system. Index cells in row-major order. Each equation is stored as one Python integer: bits
0..N-1are the coefficients and bitNis the right-hand side. A row operation is then a single XOR. - Gauss-Jordan elimination. For each column, find a row with a 1 there, swap it into the pivot position, and XOR it into every other row that has a 1 in that column. This yields reduced row echelon form.
- Consistency. A row with all coefficients zero but right-hand side 1 means no solution exists, so return
None. - Solutions. Setting all free variables to 0 gives a particular solution
x0, where each pivot variable equals its row's right-hand side. For each free variablef, settingf = 1and the other free variables to 0 gives a null-space basis vector, where each pivot variable equals its row's coefficient in columnf. - Minimise. Every solution is
x0XOR some combination of basis vectors. The null space has dimensiond <= min(m, n) <= 10. If a press pattern has no net effect and its first row is empty, the cells in the next row are forced to be empty as well. Repeating this shows the whole pattern is empty, so a null vector is determined by its first row, which givesd <= n. The same argument on columns givesd <= m. So there are at most 1024 candidates. We enumerate all of them in Gray-code order, where each step is one XOR, count the set bits, and keep the candidate with the fewest presses. On a tie we keep the lexicographically smaller row-major coordinate list, as the statement requires.
Why it is correct
Elimination uses only invertible row operations, so the solution set is unchanged. The solutions form either the empty set or the coset x0 + ker(A). The free-variable vectors are independent and span ker(A). Because we enumerate the entire coset and apply the stated tie-break, the result is exactly the minimum-size, lexicographically smallest plan.
Complexity
With N = m*n <= 100:
- Elimination:
O(N^2)big-integer XORs, each takingO(N / w)word operations. - Enumeration:
2^dcandidates, each costingO(N)to extract coordinates, withd <= min(m, n) <= 10. - Space:
O(N^2)bits for the matrix plusO(N * d)bits for the basis.
Reference solution
from typing import List, Optional
def min_press_plan(start: List[List[int]], goal: List[List[int]]) -> Optional[List[List[int]]]:
m = len(start)
n = len(start[0]) if m else 0
if m == 0 or n == 0:
return []
size = m * n
rows = []
for r in range(m):
for c in range(n):
coeff = 0
for rr, cc in ((r, c), (r - 1, c), (r + 1, c), (r, c - 1), (r, c + 1)):
if 0 <= rr < m and 0 <= cc < n:
coeff |= 1 << (rr * n + cc)
rhs = (int(start[r][c]) ^ int(goal[r][c])) & 1
rows.append(coeff | (rhs << size))
pivot_cols = []
pivot_row = 0
for col in range(size):
found = None
for row in range(pivot_row, size):
if (rows[row] >> col) & 1:
found = row
break
if found is None:
continue
rows[pivot_row], rows[found] = rows[found], rows[pivot_row]
for row in range(size):
if row != pivot_row and ((rows[row] >> col) & 1):
rows[row] ^= rows[pivot_row]
pivot_cols.append(col)
pivot_row += 1
coeff_mask = (1 << size) - 1
for row in rows:
if (row & coeff_mask) == 0 and ((row >> size) & 1):
return None
pivot_set = set(pivot_cols)
free_cols = [col for col in range(size) if col not in pivot_set]
particular = 0
for row, col in enumerate(pivot_cols):
if (rows[row] >> size) & 1:
particular |= 1 << col
basis = []
for free in free_cols:
vector = 1 << free
for row, col in enumerate(pivot_cols):
if (rows[row] >> free) & 1:
vector |= 1 << col
basis.append(vector)
best = None
best_count = size + 1
current = particular
previous_gray = 0
for mask in range(1 << len(basis)):
if mask:
gray = mask ^ (mask >> 1)
changed = gray ^ previous_gray
current ^= basis[changed.bit_length() - 1]
previous_gray = gray
count = bin(current).count("1")
if count > best_count:
continue
coords = [
[index // n, index % n]
for index in range(size)
if (current >> index) & 1
]
if count < best_count or best is None or coords < best:
best_count = count
best = coords
return best