#include <bits/stdc++.h>
using namespace std;
#define DB(v) cerr << #v << ' ' << v << endl
#define sz(v) int(v.size())

const int N = 1009;

int n,m;

char table[N][N], went[N][N];

void prepare() {
    cin >> n >> m;
    string s;
    for(int i = 0;i < n;++i) {
        cin >> s;
        for(int j = 0;j < m; ++j) {
            table[i][j] = s[j];
        }
    }
}

bool good(int x, int y) {
    if(x >= n - 1 || y >= m - 1) return false;
    if(went[x][y] == went[x + 1][y] && went[x][y] == went[x][y + 1] && went[x][y] == went[x + 1][y + 1]) return true;
    return false;
}

void go(int x, int y) {
    for(int i = 0;i < n; ++i){
        for(int j = 0;j < m; ++j){
            went[(i + x) % n][(j + y) % m] = table[i][j];
        }
    }
  /* for(int i = 0;i < n; ++i) {
        for(int j = 0;j < m; ++j) {
            cout << went[i][j] << ' ';
        }
        cout << endl;
    }
    cout << endl;*/
}

int result() {
    int res = 0;
    for(int i = 0;i < n; ++i) {
        for(int j = 0;j < m; ++j) {
            if(good(i, j)) res++;
        }
    }
    return res;
}

int near_right() {
    int res = 0;
    for(int i = 1;i <= n; ++i) {
        for(int j = 1;j < m; ++j){
            if(table[i][j] == table[i][j+1]) res++;
        }
    }
    return res;
}

int near_up() {
    int res = 0;
    for(int i = 1;i < n; ++i) {
        for(int j = 1;j <= m; ++j) {
            if(table[i+1][j] == table[i][j]) res++;
        }
    }
    return res;
}

int main()
{
#ifdef HOME
    freopen("input.txt","r", stdin);
#else
    freopen("video.in","r",stdin);
    freopen("video.out","w",stdout);
#endif // HOME
    ios::sync_with_stdio(NULL); cin.tie(NULL);
    prepare();
    int best = 0, x;
    for(int i = 0;i < n; ++i) {
        go(i, 0);
        int cur = near_right();
        if(cur >= best) {
            best = cur;
            x = i;
        }
    }
    best = 0;
    int y;
    for(int j = 0;j < m; ++j) {
        go(0, j);
        int cur = near_up();
        if(cur >= best) {
            best = cur;
            y = j;
        }
    }
    go(x,y);
    cout << result() << endl;
   /* for(int i = 0;i < n; ++i) {
        for(int j = 0;j < m; ++j) {
            go(i, j);
            ans = max(ans, result());
        }
    }*/
    return 0;
}
