Minimum Number of Flips to Convert Binary Matrix to Zero Matrix

Given a m x n binary matrix mat. In one step, you can choose one cell and flip it and all the four neighbours of it if they exist (Flip is changing 1 to 0 and 0 to 1). A pair of cells are called neighboors if they share one edge.

Return the minimum number of steps required to convert mat to a zero matrix or -1 if you cannot.

Binary matrix is a matrix with all cells equal to 0 or 1 only.

Zero matrix is a matrix with all cells equal to 0.

Example 1:

Input: mat = [[0,0],[0,1]]
Output: 3
Explanation: One possible solution is to flip (1, 0) then (0, 1) and finally (1, 1) as shown.

思路:就是BFS,不难,难点就是board的状态表示;用bit位移,来形成个integer;注意flip bit 是next ^= 1 << (i * n  + j); 注意,一层是所有的board的点,全部变一次是一层,然后下一层,再所有的点变一次;Time: O(2^mn) Space: O( m*n * sizeof(String (m*n)))

class Solution {
    public int minFlips(int[][] mat) {
        int m = mat.length;
        int n = mat[0].length;
        int start = 0;
        for(int i = 0; i < m; i++) {
            for(int j = 0; j < n; j++) {
                start += mat[i][j] << (i * n + j);
            }
        }
        int[][] dirs = new int[][] {{0,1},{0,-1},{-1,0},{1,0}};
        Queue<Integer> queue = new LinkedList<>();
        HashSet<Integer> visited = new HashSet<>();
        queue.offer(start);
        visited.add(start);
        
        int step = 0;
        while(!queue.isEmpty()) {
            int size = queue.size();
            for(int k = 0; k < size; k++) {
                Integer node = queue.poll();
                if(node == 0) {
                    return step;
                }
                for(int i = 0; i < m; i++) {
                    for(int j = 0; j < n; j++) {
                        int next = node;
                        next ^= 1 << (i * n + j);
                        for(int[] dir: dirs) {
                            int nx = i + dir[0];
                            int ny = j + dir[1];
                            if(0 <= nx && nx < m && 0 <= ny && ny < n) {
                                next ^= 1 << (nx * n + ny);
                            }
                        }
                        if(!visited.contains(next)) {
                            visited.add(next);
                            queue.offer(next);
                        }
                    }
                }
            }
            step++;
        }
        return -1;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值