洛谷 - P10449

· · 个人记录

题意

给你一个 5 \times 5 的 01 矩阵。 其中的 0 要通过操作全部改变成 1。

操作:例如改变 (x,y) 则要改变 (x−1,y),(x+1,y),(x,y−1),(x,y+1),(x,y)。

求:是否能在 6 步以内达到要求(即整个矩阵都为 1)。

思路

第一行先用状态压缩决定修改哪几个点,剩下二到四行: 当 (x - 1, y) 要改变,则改变 (x, y)。 最后判断。

代码

#include <bits/stdc++.h>
#define ll long long
using namespace std;

int q;
int a[6][6], b[6][6];
int dx[4] = {1, 0, 0, -1}, dy[4] = {0, 1, -1, 0};
char cc;
int ans, cnt;

void change(int x, int y){
    b[x][y] ^= 1;
    for(int i = 0; i < 4; i ++){
        b[x + dx[i]][y + dy[i]] ^= 1;
    }
}

int main(){
    ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);

    cin >> q;
    while(q --){
        ans = 1e9;
        for(int i = 1; i <= 5; i ++){
            for(int j = 1; j <= 5; j ++){
                cin >> cc;
                a[i][j] = cc - '0';
            }
        }
        for(int c = 0; c < (1 << 5); c ++){
            cnt = 0;
            for(int i = 1; i <= 5; i ++){ for(int j = 1; j <= 5; j ++){ b[i][j] = a[i][j]; } }

            for(int i = 1; i <= 5; i ++){
                if((c >> (i - 1)) & 1) change(1, i), cnt ++;
            }
            for(int i = 1; i <= 4; i ++){
                for(int j = 1; j <= 5; j ++){
                    if(!b[i][j]) change(i + 1, j), cnt ++;
                }
            }
            for(int i = 1; i <= 5; i ++){
                if(!b[5][i]) cnt = 1e9;
            }
            if(cnt <= 6){
                ans = min(ans, cnt);
            }
        }
        cout << (ans == 1e9 ? -1 : ans) << '\n';
    }

    return 0;
}