二进制矩阵全零转换问题 | DFS

问题描述

在一个古老的实验室里,两个研究员,小星和小月,获得了一个 m x n 的电路图,表示为二进制矩阵 grid。在这个矩阵中,他们可以对任意一个电路单元进行翻转操作。翻转操作会将所选单元的状态从 0 改为 1,或从 1 改为 0,同时影响与其相邻的上下左右单元。

小星和小月希望通过最少的翻转次数,将整个电路图变成全 0 的状态。如果这个目标无法实现,则返回 -1


测试样例

样例1:

输入:grid = [[0, 1], [1, 0]]
输出:2

样例2:

输入:grid = [[1, 0], [1, 1]]
输出:1

样例3:

输入:grid = [[0]]
输出:0

题解:

        很经典的一道题,原题叫棋盘覆盖问题,关键在于一个位置如果翻转两次等于没有翻转

        所以直接DFS遍历每个格子,每次都有翻和不翻两个情况,最后判断翻转次数即可。

        有一种更方便的方法,但是在时间上似乎不那么占优,先通过DFS生成随机1,0的长度为m*n的字符串,然后根据字符串的10,如果是1就翻转,如果是0就不翻,也不用每一位去异或,直接在对应位置+1代表翻转次数,最后遍历,如果是偶数就是0,奇数就是1即可。

代码:

#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
using namespace std;
typedef long long int ll;

vector> grid1;
vector> vt;


int mincnt=100000;
int xt[5]={1,0,-1,0,0};
int yt[5]={0,1,0,-1,0};

int check(int x,int y){
    int n=vt.size();
    int m=vt[0].size();
    if(x>=0 && x=0 && y> grid) {
    vt=grid;
    grid1=grid;
    string s="";
    mincnt=100000;
    int x=grid.size();
    int y=grid[0].size();
    dfs(s,0,x*y);
    if(mincnt==100000){
        return -1;
    }
    return mincnt;
}

int main() {
    cout << (solution({{1, 0, 1}, {0, 1, 0}, {1, 0, 1}})) << endl;
    cout << (solution({{0, 1}, {1, 0}}) == 2) << endl;
    cout << (solution({{1, 0}, {1, 1}}) == 1) << endl;
    cout << (solution({{0, 0}, {0, 1}}) == 3) << endl;
    //cout << (solution({{0}}) == 0) << endl;
    return 0;
}

你可能感兴趣的:(深度优先,算法)