飞行员兄弟Java
暴力枚举,就是太慢了,得四秒多
java样例
import java.util.*;
public class Main {
static char[][] g = new char[4][4];
static char[][] backup = new char[4][4];
static List<String> list = new ArrayList<>();
static List<String> temp = new ArrayList<>();
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
for(int i=0;i<4;i++) {
g[i]=sc.nextLine().toCharArray();
backup[i]=Arrays.copyOf(g[i], 4);
}
//枚举2的16次方中方案
int minStep = Integer.MAX_VALUE;
for(int op=0;op<(1<<16);op++) {
//每种方案的步骤数
int step = 0;
for(int i=0;i<16;i++) {
if((op>>i&1)==1) {
int x = i/4;
int y = i%4;
temp.add((x+1)+" "+(y+1));
step++;
turn(x,y);
}
}
boolean flag = false;
for(int i=0;i<4;i++) {
for(int j=0;j<4;j++) {
if(g[i][j]=='+') {
flag = true;
break;
}
}
if(flag)
break;
}
//方案正确的情况下,检查step是否最小
if(!flag) {
if(step<minStep) {
list.clear();
minStep = step;
for(String x : temp) {
list.add(x);
}
}
}
//临时集合清空
temp.clear();
//第i轮循环结束,恢复g状态
for(int i=0;i<4;i++) {
g[i]=Arrays.copyOf(backup[i], 4);
}
}
System.out.println(minStep);
for(String x:list) {
System.out.println(x);
}
}
static int[] x = {-3,-2,-1,1,2,3,0,0,0,0,0,0,0};
static int[] y = {0,0,0,0,0,0,-3,-2,-1,1,2,3,0};
public static void turn(int a,int b) {
for(int i=0;i<x.length;i++) {
int p = a+x[i];
int q = b+y[i];
if(p<0 || p>=4 || q<0 || q>= 4) {
continue;
}
if(g[p][q]=='+') g[p][q]='-';
else g[p][q]='+';
}
}
}