#include <bits/stdc++.h>
using namespace std;
int n, m;
vector<string> f, nf;
int main() {
  ios::sync_with_stdio(0), cin.tie(0);
  cin >> n >> m;
  f.resize(n);
  for (int i = 0; i < n; ++i) cin >> f[i];
  if (n >= 4 && m >= 4) {
    cout << -1;
    return 0;
  }
  if (n == 1 || m == 1) {
    cout << 0;
    return 0;
  }
  if (n > m) {
    nf.resize(m);
    for (int i = 0; i < m; ++i) {
      string s;
      for (int j = 0; j < n; ++j) nf[i] += f[j][i];
    }
    f = nf;
    swap(n, m);
  }
  if (n == 2) {
    vector<int> v(m);
    for (int i = 0; i < m; ++i) v[i] = f[0][i] - '0' + f[1][i] - '0';
    vector<int> cv = v;
    int cnt1 = 0;
    for (int i = 1; i < m; ++i)
      if ((cv[i - 1] + cv[i]) % 2 == 0) ++cnt1, ++cv[i];
    cv = v;
    int cnt2 = 1;
    ++cv[0];
    for (int i = 1; i < m; ++i)
      if ((cv[i - 1] + cv[i]) % 2 == 0) ++cnt2, ++cv[i];
    cout << min(cnt1, cnt2);
    return 0;
  }
  vector<int> a(m), b(m);
  for (int i = 0; i < m; ++i) {
    a[i] = f[0][i] - '0' + f[1][i] - '0';
    b[i] = f[1][i] - '0' + f[2][i] - '0';
  }
  vector<int> ca = a, cb = b;
  int cnt1 = 0;
  for (int i = 1; i < m; ++i) {
    bool chk1 = (ca[i - 1] + ca[i]) % 2 == 0;
    bool chk2 = (cb[i - 1] + cb[i]) % 2 == 0;
    if (!chk1 && !chk2) continue;
    if (chk1) ++ca[i];
    if (chk2) ++cb[i];
    ++cnt1;
  }
  ca = a;
  cb = b;
  int cnt2 = 1;
  ++ca[0];
  for (int i = 1; i < m; ++i) {
    bool chk1 = (ca[i - 1] + ca[i]) % 2 == 0;
    bool chk2 = (cb[i - 1] + cb[i]) % 2 == 0;
    if (!chk1 && !chk2) continue;
    if (chk1) ++ca[i];
    if (chk2) ++cb[i];
    ++cnt2;
  }
  ca = a;
  cb = b;
  int cnt3 = 1;
  ++cb[0];
  for (int i = 1; i < m; ++i) {
    bool chk1 = (ca[i - 1] + ca[i]) % 2 == 0;
    bool chk2 = (cb[i - 1] + cb[i]) % 2 == 0;
    if (!chk1 && !chk2) continue;
    if (chk1) ++ca[i];
    if (chk2) ++cb[i];
    ++cnt3;
  }
  ca = a;
  cb = b;
  int cnt4 = 1;
  ++ca[0];
  ++cb[0];
  for (int i = 1; i < m; ++i) {
    bool chk1 = (ca[i - 1] + ca[i]) % 2 == 0;
    bool chk2 = (cb[i - 1] + cb[i]) % 2 == 0;
    if (!chk1 && !chk2) continue;
    if (chk1) ++ca[i];
    if (chk2) ++cb[i];
    ++cnt4;
  }
  cout << min({cnt1, cnt2, cnt3, cnt4});
}
