阿里巴巴2021校招

static List<String> val = new ArrayList<>();
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
int a = 1;
for (int i = 0; i < num; i++) {
int N = sc.nextInt();
int L = sc.nextInt();
int[][] arr = getInput(N, L, sc);
int[][] targetArr = getInput(N, L, sc);
getPath(arr, targetArr);
}
for (String s : val) {
System.out.println(s);
}
}
public static int[][] getInput(int N, int L, Scanner sc) {
int[][] arr = new int[N][L];
for (int j = 0; j < N; j++) {
String next = sc.next();
for (int k = 0; k < L; k++) {
arr[j][k] = next.charAt(k) & 1;
}
}
return arr;
}
public static void getPath(int[][] arr, int[][] targetArr) {
int pre = Integer.MIN_VALUE;
int index = 0;
if (index == 0 && getWay(arr, targetArr)) {
val.add(0 + "");
return;
}
while (true) {
index++;
int maxDiff = getMaxDiff(arr, targetArr);
setVal(arr, maxDiff);
if (getWay(arr, targetArr)) {
val.add(index + "");
break;
}
if (maxDiff == -1||maxDiff == pre || index == arr[0].length) {
val.add("impossible");
break;
}
pre = maxDiff;
}
}
public static int getMaxDiff(int[][] arr, int[][] targetArr) {
for (int j = 0; j < targetArr[0].length; j++) {
int count = 0;
int targetCount = 0;
for (int i = 0; i < targetArr.length; i++) {
count += targetArr[i][j];
}
for (int i = 0; i < arr.length; i++) {
targetCount += arr[i][j];
}
if (count + targetCount == arr.length) {
return j;
}
}
return -1;
}
public static void setVal(int[][] arr, int L) {
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[j].length; j++) {
if (j == L) {
if (arr[i][j] == 1) {
arr[i][j] = 0;
}else{
arr[i][j] = 1;
}
}
}
}
}
public static boolean getWay(int[][] arr, int[][] targetArr) {
List<String> arrList = new ArrayList<>();
List<String> targetList = new ArrayList<>();
for (int i = 0; i < arr.length; i++) {
String str = "";
for (int e : arr[i]) {
str += e;
}
arrList.add(str);
}
for (int i = 0; i < targetArr.length; i++) {
String str = "";
for (int e : targetArr[i]) {
str += e;
}
targetList.add(str);
}
boolean[] flag = new boolean[arr.length];
for (String str : arrList) {
if (targetList.indexOf(str) != -1 && flag[targetList.indexOf(str)] != true) {
flag[targetList.indexOf(str)] = true;
}
}
for (boolean e : flag) {
if (!e) {
return false;
}
}
return true;
}