1284. Minimum Number of Flips to Convert Binary Matrix to Zero Matrix

BFS

T: O(m*n + 2^(m*n)), 1 <= m, n <= 3
S: 2^(m*n)
class Solution {
    private static final int[][] DIRS = {{0,1}, {1,0}, {0,-1}, {-1,0}};
    private record Step(int state, int level){};
    public int minFlips(int[][] mat) {
        int m = mat.length;
        int n = mat[0].length;

        int state = 0;
        for (int i = m -1 ; i >= 0; i--) { // [0,0], [0,1] -> become 1000 -> 8
            for (int j = n - 1; j >= 0; j--) {
                state <<= 1; // left shift to have space
                state |= mat[i][j]; // set value, so the first value will be in left side, but we start from end, so [0,0] will be in most right side
            }
        }
        // System.out.println(state);

        Set<Integer> visited = new HashSet<>();
        Queue<Step> queue = new LinkedList<>();
        queue.offer(new Step(state, 0));

        while (!queue.isEmpty()) {
            Step cur = queue.poll();
            if (visited.contains(cur.state)) {
                continue;
            }
            visited.add(cur.state);
            if (cur.state == 0) {
                return cur.level;
            }
            // try each cell to do flip
            for (int i = 0; i < m; i++) {
                for (int j = 0; j < n; j++) {
                    // flip this cell
                    int newState = cur.state;
                    int mask = 1 << (i*n + j); // move to that cell's position
                    newState ^= mask;

                    // then flip this cell's neights value
                    for (int[] dir: DIRS) {
                        int x = i + dir[0];
                        int y = j + dir[1];
                        if (x < 0 || x >= m || y < 0 || y >= n) {
                            continue;
                        }
                        mask = 1 << (x*n + y);
                        newState ^= mask;

                    }
                    // after flip values, go to next round
                    queue.offer(new Step(newState, cur.level+1));
                }
            }
        }

        return -1;
    }
}
/**
state: 2^(m*n) 
so 
T: O(m*n + 2^(m*n)), 1 <= m, n <= 3
S: 2^(m*n)

 */

use bit

Last updated

Was this helpful?