#include<bits/stdc++.h>
using namespace std;

#define xx first
#define yy second
typedef long long ll;
typedef pair<int, int> pii;

int a[1002][1002], b[1002][1002];

int main()
{
    freopen("video.in", "r", stdin);
    freopen("video.out", "w", stdout);
    int n, m;
    cin >> n >> m;
    //char qq = getchar();
    for(int i = 0; i < n; i++)
    {
        for(int j = 0; j < m; j++)
        {
            char c;
            //c = getchar();
            cin >> c;
            a[i][j] = c - '0';
        }
        //qq = getchar();
    }
    int min_n = 10000, min_m = 10000, it, jt;
    for(int j = 0; j < m; j++)
    {
        int ans = 0;
        int pj = j-1;
        if(j == 0)
            pj = m-1;
        for(int i = 0; i < n; i++)
            if(a[i][j] == a[i][pj])
                ans++;
        if(ans < min_m)
        {
            min_m = ans;
            jt = j;
        }
    }
    for(int i = 0; i < n; i++)
    {
        int ans = 0;
        int pi = i - 1;
        if (i == 0)
            pi = n-1;
        for(int j = 0; j < m; j++)
            if(a[i][j] == a[pi][j])
                ans++;
        if(ans < min_n)
        {
            min_n = ans;
            it = i;
        }
    }
    for(int i = it, ni = 0; ni < n; i = (i + 1)%n, ni++)
    {
        for(int j = jt, nj = 0; nj < m; j = (j+1)%m, nj++)
        {
            b[ni][nj] = a[i][j];
        }
    }
    int ans = 0;
    for(int i = 1; i < n; i++)
    {
        for(int j = 1; j < m; j++)
        {
            if(b[i][j] == b[i-1][j] && b[i][j-1] == b[i-1][j-1] && b[i-1][j] == b[i][j-1])
            {
                ans++;
                //cout << i << " " << j << "\n";
            }
        }
    }
    cout << ans;
}
