95. 费解的开关(Acwing)(分析+递推)

95. 费解的开关

题目链接:
https://www.acwing.com/problem/content/97/

题解:

前一行的状态可以决定后一行的按法,因为一个开关按两次等于没按,所以第一行的状态确定了,第二行就必须那么按,我们可以枚举第一行的按法,然后进行模拟,因为一行有5个框框,就有32种按法,用5位的二进制表示,例如00001表示,按第5个(1表示按,0表示不按)

AC代码:

public class NO95 {
    static int t;
    static int N = 6;
    static char[][] arr = new char[N][N];
    static char[][] temp = new char[N][N];
    static int[] dx = {0, -1, 1, 0, 0};
    static int[] dy = {0, 0, 0, -1, 1};

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

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        t = sc.nextInt();
        while (t-- > 0) {
            for (int i = 0; i < 5; i++) {
                arr[i] = sc.next().toCharArray();
            }
            int res = 10;
            for (int i = 0; i < 32; i++) { // 枚举第1行按法
                int step = 0;
                for (int j = 0; j < 5; j++) temp[j] = Arrays.copyOf(arr[j], arr[j].length);

                for (int j = 0; j < 5; j++) { // 1代表按j,0代表不按j
                    if ((i >> j & 1) == 1) {
                        step++;
                        turn(0, j);
                    }
                }

                for (int j = 0; j < 4; j++) {
                    for (int k = 0; k < 5; k++) {
                        if (arr[j][k] == ‘0‘) {
                            step++;
                            turn(j + 1, k);
                        }
                    }
                }
                boolean flag = true;
                for (int j = 0; j < 5; j++) {
                    if (arr[4][j] == ‘0‘) {
                        flag = false;
                        break;
                    }
                }
                if (flag) {
                    if (step < res) res = step;
                }
                for (int j = 0; j < 5; j++) arr[j] = Arrays.copyOf(temp[j], temp[j].length);
            }
            if (res <= 6) System.out.println(res);
            else System.out.println(-1);
        }
    }
}

95. 费解的开关(Acwing)(分析+递推)

上一篇:CentOS 7 不能连接Kvm虚拟机console.....


下一篇:如何从命令行实时监控Nginx Web服务器