1
// Helper counts how many ones are in the matrix to start with. O(mn)2
var countOnes = function (mat) {4
for (let r = 0; r < mat.length; r++) {5
count += mat[r].reduce((a, b) => a + b);10
// Helper flips a cell and its neighbors. Returns updated number of ones left in matrix. O(1)11
var flip = function (mat, r, c, numOnes) {19
dirs.forEach((el) => {22
if (newR >= 0 && newR < mat.length && newC >= 0 && newC < mat[0].length) {23
if (mat[newR][newC] === 0) {35
// Main function tries every possible combination of cells being flipped using backtracking. O (2^(mn))36
var minFlips = function (mat) {37
const rows = mat.length,39
let minFlips = Infinity,40
numOnes = countOnes(mat);42
var backtrackFlip = function (cell, flips) {43
if (numOnes === 0) minFlips = Math.min(minFlips, flips);44
for (let newCell = cell; newCell < rows * cols; newCell++) {45
// Function uses a cell number instead of row / col to keep track of column flips46
// For example, a 2 x 2 grid has cells "0", "1", "2", "3" and the line below calculates row / col based on that number47
const r = Math.floor(newCell / cols),49
numOnes = flip(mat, r, c, numOnes);50
backtrackFlip(newCell + 1, flips + 1);51
numOnes = flip(mat, r, c, numOnes);56
return minFlips === Infinity ? -1 : minFlips;