import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
/**
* 행렬
*/
public class Main {
static int N, M;
static int[][] A, B;
public static void main(String[] args) throws IOException {
init();
int cnt = getCnt();
printCnt(cnt);
}
private static void init() throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
N = Integer.parseInt(st.nextToken());
M = Integer.parseInt(st.nextToken());
A = new int[N][M];
B = new int[N][M];
initArray(br, A);
initArray(br, B);
}
private static void initArray(BufferedReader br, int[][] arr) throws IOException {
for (int i = 0; i < N; i++) {
String s = br.readLine();
for (int j = 0; j < M; j++) {
arr[i][j] = s.charAt(j) - '0';
}
}
}
private static int getCnt() {
int cnt = 0;
for (int i = 0; i < N - 2; i++) {
for (int j = 0; j < M - 2; j++) {
if (A[i][j] != B[i][j]) {
flipArray(i, j);
cnt++;
}
}
}
return cnt;
}
private static void flipArray(int row, int col) {
for (int i = row; i < row + 3; i++) {
for (int j = col; j < col + 3; j++) {
A[i][j] = Math.abs(A[i][j] - 1);
}
}
}
private static boolean checkArray() {
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
if (A[i][j] != B[i][j]) {
return false;
}
}
}
return true;
}
private static void printCnt(int cnt) {
if (checkArray()) {
System.out.println(cnt);
} else {
System.out.println(-1);
}
}
}
A
를 순회하면서 해당 위치가 B
와 같은지 다른지를 판별한다.N-2
번 행까지, 열은 M-2
열 까지만 순회한다. (3 X 3 영역의 값을 바꿀 것이므로) - getCnt()
A
와 B
의 값이 다르다면, 해당 위치를 시작으로 3 X 3 영역의 값을 바꾸고 cnt
값을 증가시킨다. - flipArray()
A
와 B
가 같은지를 확인하고, 같다면 cnt
값을, 다르다면 -1
을 출력한다. - printCnt(), checkArray()