Confused switch - recursion

Confused switch - recursion

Inexplicable switch
After reading a few answers, I feel that the writing is not very clear. Here is a record of my understanding.
The most important thing in this question is to find out whether all the lights can be turned on at the end, regardless of the order of lighting . That is to say, as long as you determine which lights to turn on, no matter which one comes first, you will get the same answer.
So where is the recursion reflected?
As long as we determine the operation method of the first line, which moves and which does not move it, the result will be determined accordingly. For each subsequent line, we only need to decide whether or not to operate according to the on-off condition of the corresponding position of the previous line.
In this way, whether it can be fully lit in the end will be reflected in the last line. You only need to judge whether the last line is fully lit to get the answer. This
question has the meaning of state compression DP , which further strengthens the bit operation.
The difficulty is that this recursion is more difficult to detect

#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;

const int N = 6;
char g[N][N], backup[N][N];
int dx[5] = {
    
    -1, 0, 1, 0, 0}, dy[5] = {
    
    0, 1, 0, -1, 0};

void turn(int x, int y) {
    
    
    for (int i = 0; i < 5; i++) {
    
    
        int a = x + dx[i], b = y + dy[i];
        if (a < 0 || a >= 5 || b < 0 || b >= 5) continue;
        
        g[a][b] ^= 1;
    }
}

int main() {
    
    
    int T;
    cin >> T;
    
    while(T--) {
    
    
        for(int i = 0; i < 5; i++) cin >> g[i];
        int res = 10;
        for (int i = 0; i < (1 << 5); i++) {
    
     // 枚举第一行所有可能的操作方法
            memcpy(backup, g, sizeof g); // 保存最初始的状态
            int step = 0; // 记录操作次数
            for (int j = 0; j < 5; j++) {
    
    
                if (i >> j & 1) {
    
    
                    turn(0, j);
                    step++;
                }
            }
            for (int i = 0; i < 4; i++) //后面的每一行中的每一格是否操作,取决于它的上一格
                for (int j = 0; j < 5; j++) {
    
    
                    if (g[i][j] == '0') {
    
    
                        turn(i+1, j);
                        step++;
                    }
                }
            
            bool isdark = false; // 遍历最后一行是否全亮即可得到答案
            for (int i = 0; i < 5; i++)
                if (g[4][i] == '0') isdark = true;
            
            if (!isdark) res = min(res, step);
            memcpy(g, backup, sizeof backup); // 还原成最初始的状态
        }
        if (res > 6) res = -1;
        cout << res << endl;
    }
    
    return 0;
}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=324122379&siteId=291194637