AcWing 95. 【java】费解的开关
原题链接
中等
作者:
tt2767
,
2019-12-08 15:34:14
,
所有人可见
,
阅读 1004
// 要根据题意特判下6 😭
import java.util.*;
public class Main{
int solve(int status){
int[][] map = new int[7][7];
for (int x = 1 ; x <= 5; x++) map[x] = lights[x].clone();
int cnt = 0;
for (int k = 1; k <=5 ; k++ ){
// if (((status >> (k-1)) & 1) != map[1][k] ){ 有个地方没明白为什么这两个判断都能过
if (((status >> (k-1)) & 1) == 1 ){
cnt++;
flip(map,1, k);
}
}
for (int x = 2 ; x<= 5; x++){
for (int y = 1 ; y <= 5; y++){
if (map[x-1][y] == 0){
cnt+=1;
flip(map, x, y);
}
}
}
for (int k = 1 ;k <= 5 ; k++){
if (map[5][k] == 0){
return Integer.MAX_VALUE;
}
}
return cnt;
}
int work(int[][] lights){
int min_step = Integer.MAX_VALUE;
for (int j = 0; j < (1 << 5); j++){
min_step = Math.min(min_step, solve(j));
}
return min_step;
}
void run(){
int n = jin.nextInt();
for (int i = 0 ; i < n ; i++){
for (int j = 1; j <= 5 ; j++){
char[] row = jin.next().toCharArray();
for (int k = 0; k < 5 ; k++){
lights[j][k+1] = row[k]-'0';
}
}
int min_step = work(lights);
System.out.println(min_step > 6 ? -1 : min_step);
}
}
void flip(int[][]map , int x, int y){
for (int i = 0 ; i < 5 ; i++){
int nx = dx[i] + x;
int ny = dy[i] + y;
map[nx][ny] ^= 1;
}
}
private int[] dx = {0, 1, -1, 0, 0};
private int[] dy = {0, 0, 0, 1, -1};
private int[][] lights = new int[7][7];
private Scanner jin = new Scanner(System.in);
public static void main(String[] args) throws Exception {new Main().run();}
}