C++实现:https://blog.csdn.net/moon_sky1999/article/details/75127657
Java代码:
import java.io.*;
import java.math.*;
import java.util.*;
public class Main {
static int dx[] = {1, -1, 0, 0};
static int dy[] = {0, 0, 1, -1};
static int a[][];
static boolean vis[];
public static int get_num() {
int pos = 0;
for (int i = 1; i <= 4; ++i) {
for (int j = 1; j <= 4; ++j) {
if (a[i][j] == 1) {
int c = (i - 1) * 4 + j;
pos = (pos | (1 << (c - 1)));
}
}
}
return pos;
}
public static void move_back(int pos) {
for (int i = 1; i <= 4; ++i) {
for (int j = 1; j <= 4; ++j) {
int c = (i - 1) * 4 + j;
if ((pos & (1 << (c - 1))) != 0) a[i][j] = 1;
else a[i][j] = 0;
}
}
}
public static void flip(int i, int j) {
a[i][j] = 1 - a[i][j];
for (int k = 0; k < 4; ++k) {
if (i + dx[k] >= 1 && i + dx[k] <= 4 && j + dy[k] >= 1 && j + dy[k] <= 4) {
a[i + dx[k]][j + dy[k]] = 1 - a[i + dx[k]][j + dy[k]];
}
}
}
public static void main(String[] args) {
a = new int[5][5];
vis = new boolean[200000];
for (int j = 0; j < vis.length - 1; ++j)
vis[j] = false;
Scanner cin = new Scanner(System.in);
for (int i = 1; i <= 4; ++i) {
String s = cin.nextLine();
for (int j = 0; j < 4; ++j) {
if (s.charAt(j) == 'w')
a[i][j + 1] = 1;
else a[i][j + 1] = 0;
}
}
int pos = get_num();
vis[pos] = true;
Queue<Integer> p = new LinkedList<Integer>(), q = new LinkedList<Integer>();
((LinkedList<Integer>) q).push(pos);
int tot = 0;
boolean ok = false;
while (!q.isEmpty()) {
int x = ((LinkedList<Integer>) q).getFirst();
((LinkedList<Integer>) q).pop();
if (x == 0 || x == 65535) {
ok = true;
break;
}
move_back(x);
for (int i = 1; i <= 4; ++i) {
for (int j = 1; j <= 4; ++j) {
flip(i, j);
int e = get_num();
if (vis[e] == false) {
vis[e] = true;
((LinkedList<Integer>) p).push(e);
}
flip(i, j);
}
}
if(q.isEmpty()){
++tot;
while(!p.isEmpty()){
((LinkedList<Integer>) q).push(((LinkedList<Integer>) p).getFirst());
((LinkedList<Integer>) p).pop();
}
}
}
if(ok==true)
System.out.println(tot);
else System.out.println("Impossible");
}
}