#include <bits/stdc++.h>

#define vec vector
#define pb push_back
#define all(a) a.begin(), a.end()
#define re return
#define forn(i, n) for (int i = 0; i < n; i++)

using namespace std;

int n, m;
char a[1007][1007], b[1007][1007];

bool ok(char a, char b, char c, char d)
{
    vec<char> q;
    q.pb(a);q.pb(b);q.pb(c);q.pb(d);
    sort(all(q));
    forn(i, 4)
        if (q[0] != q[i])
            re false;
    re true;
}

int get(char a[1007][1007])
{
    int ans = 0;
    forn(i, n - 1)
        forn(j, m - 1)
            if (ok(a[i][j], a[i + 1][j], a[i][j + 1], a[i + 1][j + 1]))
                ans++;
    return ans;
}

int ask(char dd[1007][1007])
{
    int it = 0;
    char a[1007][1007];
    forn(i, n)
        forn(j, m)
            a[i][j] = dd[i][j];
    int ans = get(a);
    while(true)
    {
        if (it > m + 1)
            break;
        forn(i, m)
            b[0][i] = a[n - 1][i];
        for (int i = 1; i < n; i++)
            forn(j, m)
                b[i][j] = a[i - 1][j];
        int d = get(b);
        if (d >= ans)
        {
            ans = d;
            forn(i, n)
                forn(j, m)
                    a[i][j] = b[i][j];
        }
        else
            break;
        it++;
    }
    re ans;
}

int main()
{
    freopen("video.in", "r", stdin);
    freopen("video.out", "w", stdout);
    cin >> n >> m;
    forn(i, n)
        forn(j, m)
            cin >> a[i][j];
    int ans = get(a);
    int it = 0;
    while(true)
    {
        if (it > n + 1)
            break;
        ans = max(ans, ask(a));
        forn(i, n)
            b[i][0] = a[i][m - 1];
        forn(i, n)
            for (int j = 1; j < m; j++)
                b[i][j] = a[i][j - 1];
        int d = get(b);
        if (d >= ans)
        {
            ans = d;
            forn(i, n)
                forn(j, m)
                    a[i][j] = b[i][j];
        }
        else
            break;
        it++;
    }
    cout << ans;
}
