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

const int MAXN = (int)3e2 + 22;
const int dx[4] = { 0, 0, 1, 1 };
const int dy[4] = { 0, 1, 0, 1 };

char mm[MAXN][MAXN];
char go[MAXN][MAXN];

int n, m, cnt;

char lol[MAXN];
char kek[4];

void input()
{
	scanf("%d %d\n", &n, &m);
	for (int i = 0; i < n; i++)
	{
		for (int j = 0; j < m; j++)
			scanf("%c", &mm[i][j]);
		getchar();
	}
}

inline bool good(int x, int y)
{
	int nx, ny;
	for (int k = 0; k < 4; k++)
	{
		nx = (x + dx[k]) % n;
		ny = (y + dy[k]) % m;
		kek[k] = go[nx][ny];
	}
	return kek[0] == kek[1] && kek[1] == kek[2] && kek[2] == kek[3];
}

void INIT()
{
	for (int i = 0; i < n; i++)
	{
		for (int j = 0; j < m; j++)
		{
			go[i][j] = mm[i][j];
		}
	}
	for (int i = 0; i < n - 1; i++)
	{
		for (int j = 0; j < m - 1; j++)
		{
			if (good(i, j))
				cnt++;
		}
	}
}

void up()
{
	for (int i = 0; i < m; i++)
	{
		lol[i] = go[0][i];
		if (i + 1 < m && good(0, i))
			cnt--;
	}
	for (int i = 0; i < n - 1; i++)
	{
		for (int j = 0; j < m; j++)
			go[i][j] = go[i + 1][j];
	}
	for (int i = 0; i < m; i++)
		go[n - 1][i] = lol[i];
	for (int i = 0; i < m - 1; i++)
	{
		if (good(n - 2, i))
			cnt++;
	}
}

void left()
{
	for (int i = 0; i < n; i++)
	{
		lol[i] = go[i][0];
		if (i + 1 < n && good(i, 0))
			cnt--;
	}
	for (int i = 0; i < n; i++)
	{
		for (int j = 0; j < m - 1; j++)
			go[i][j] = go[i][j + 1];
	}
	for (int i = 0; i < n; i++)
		go[i][m - 1] = lol[i];
	for (int i = 0; i < n - 1; i++)
	{
		if (good(i, m - 2))
			cnt++;
	}
}

void right()
{
	for (int i = 0; i < n; i++)
	{
		lol[i] = go[i][m - 1];
		if (i + 1 < n && good(i, m - 2))
			cnt--;
	}
	for (int i = 0; i < n; i++)
	{
		for (int j = m - 1; j > 0; j--)
			go[i][j] = go[i][j - 1];
	}
	for (int i = 0; i < n; i++)
		go[i][0] = lol[i];
	for (int i = 0; i < n - 1; i++)
	{
		if (good(i, 0))
			cnt++;
	}
}

int main()
{
	// xxxvideo
	freopen("video.in", "r", stdin);
	freopen("video.out", "w", stdout);
	input();
	INIT();
	int ans = cnt;
	int j, d;
	for (int i = 0; i < n; i++)
	{
		if (i & 1)
			j = m - 1, d = -1;
		else
			j = 0, d = 1;
		while (j >= 0 && j < m)
		{
			j += d;
			if (d == 1)
				right();
			else
				left();
			ans = max(ans, cnt);
		}
		up();
		ans = max(ans, cnt);
	}
	printf("%d", ans);
	return 0;
}