1171. Silence the Board

Hard7.5 points estimatedEnumerationBitmaskMatrixBrainteaser

A control panel is an m x n grid of lights, where lights[r][c] is true when that light is on. Pressing a cell toggles that light and its up, down, left and right neighbours (those that exist). Each cell is worth pressing at most once, since pressing twice cancels out, and the order of presses does not matter.

Return the minimum total number of presses that turns every light off, or -1 if it is impossible. Here 1 <= m <= 16 and 1 <= n <= 12.

Choose the presses of the first row among all 2^n patterns; every later row is then forced by the lights still on above it. This runs in O(2^n * m) time with bitmasks and O(m) space.

Example 1

Input:
lights = [[true]]
Output:
1
Explanation:

A single lit cell needs one press.

Example 2

Input:
lights = [[false,false],[false,false]]
Output:
0
Explanation:

Every light is already off.

Example 3

Input:
lights = [[false,true,false],[true,true,true],[false,true,false]]
Output:
1
Explanation:

Pressing the centre toggles exactly the five lit cells of the plus shape.

Constraints

1 ≤ m ≤ 16

1 ≤ n ≤ 12

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.

Expected complexity

Time
O(2^n * m)
Space
O(m)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…