#include <iostream>
#include <cstdio>
#include <vector>
using namespace std;

int main() {
    freopen("video.in", "r", stdin);
    freopen("video.out", "w", stdout);
    int n, m;
    cin >> n >> m;
    vector <vector <bool> > data(n, vector <bool> (m, 0));
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            char x;
            cin >> x;
            if (x == '1') data[i][j] = 0; else data[i][j] = 1;
        }
    }
    int str = 0, minstr = 1e9;
    int size = 0;
    for (int i = 0; i < n; i++) {
        size = 0;
        for (int j = 0; j < m; j++) {
            if (data[i][j] == data[(i + 1) % n][j] && data[(i + 1) % n][(j + 1) % m] == data[i][(j + 1) % m] && data[(i + 1) % n][j] == data[i][(j + 1) % m] ) {
                size++;
            }
        }
        if (size < minstr) {
            minstr = size;
            str = i;
        }
    }
    int stolb = 0, minstolb = 1e9;
    size = 0;
    for (int j = 0; j < m; j++) {
        size = 0;
        for (int i = 0; i < n; i++) {
            if (data[i][j] == data[i][(j + 1) % m] && data[(i + 1) % n][j] == data[(i + 1) % n][(j + 1) % m] && data[i][j] == data[(i + 1) % n][(j + 1) % m]) {
                size++;
            }
        }
        if (size < minstolb) {
            minstolb = size;
            stolb = j;
        }
    }
    int x = str + 1;
    int y = stolb + 1;
    size = 0;
   // cout << str << " " << stolb << endl;
    for (int i = 0; i < n - 1; i++) {
        y = (stolb + 1);
        if (x == n) x = 0;
        for (int j = 0; j < m - 1; j++) {
            if (y == m) y = 0;
            int k = (x + 1) % n, l = (y + 1) % m;
            if (data[x][y] == data[k][y] && data[k][y] == data[k][l] && data[k][l] == data[x][l]) size++;
            y++;
        }
        x++;
    }
    cout << size;
}
