|
| 1 | +/** |
| 2 | + * 1284. Minimum Number of Flips to Convert Binary Matrix to Zero Matrix |
| 3 | + * https://leetcode.com/problems/minimum-number-of-flips-to-convert-binary-matrix-to-zero-matrix/ |
| 4 | + * Difficulty: Hard |
| 5 | + * |
| 6 | + * Given a m x n binary matrix mat. In one step, you can choose one cell and flip it and all the |
| 7 | + * four neighbors of it if they exist (Flip is changing 1 to 0 and 0 to 1). A pair of cells are |
| 8 | + * called neighbors if they share one edge. |
| 9 | + * |
| 10 | + * Return the minimum number of steps required to convert mat to a zero matrix or -1 if you cannot. |
| 11 | + * |
| 12 | + * A binary matrix is a matrix with all cells equal to 0 or 1 only. |
| 13 | + * |
| 14 | + * A zero matrix is a matrix with all cells equal to 0. |
| 15 | + */ |
| 16 | + |
| 17 | +/** |
| 18 | + * @param {number[][]} mat |
| 19 | + * @return {number} |
| 20 | + */ |
| 21 | +var minFlips = function(mat) { |
| 22 | + const rows = mat.length; |
| 23 | + const cols = mat[0].length; |
| 24 | + const target = 0; |
| 25 | + const start = mat.flat().reduce((acc, val, idx) => acc | (val << idx), 0); |
| 26 | + const queue = [[start, 0]]; |
| 27 | + const seen = new Set([start]); |
| 28 | + const directions = [[0, 0], [0, 1], [0, -1], [1, 0], [-1, 0]]; |
| 29 | + |
| 30 | + while (queue.length) { |
| 31 | + const [state, steps] = queue.shift(); |
| 32 | + |
| 33 | + if (state === target) return steps; |
| 34 | + |
| 35 | + for (let i = 0; i < rows; i++) { |
| 36 | + for (let j = 0; j < cols; j++) { |
| 37 | + let nextState = state; |
| 38 | + for (const [di, dj] of directions) { |
| 39 | + const ni = i + di; |
| 40 | + const nj = j + dj; |
| 41 | + if (ni >= 0 && ni < rows && nj >= 0 && nj < cols) { |
| 42 | + const pos = ni * cols + nj; |
| 43 | + nextState ^= (1 << pos); |
| 44 | + } |
| 45 | + } |
| 46 | + if (!seen.has(nextState)) { |
| 47 | + seen.add(nextState); |
| 48 | + queue.push([nextState, steps + 1]); |
| 49 | + } |
| 50 | + } |
| 51 | + } |
| 52 | + } |
| 53 | + |
| 54 | + return -1; |
| 55 | +}; |
0 commit comments