#define _CRT_SECURE_NO_WARNINGS
#include <cstdio>
#include <iostream>
#include <cstring>
#include <algorithm>
#include <string>
using namespace std;

const int MAXN = 1e3 + 111;

int n, m;

int ans, ans1 = MAXN * MAXN, ans2 = MAXN * MAXN;

string s[MAXN];

int gg1(int id)
{
	int ans = 0;
	for (int i = 0; i < m; i++)
	{
		char x1 = s[id][i];
		char x2 = s[(id + 1) % n][i];
		char x3 = s[id][(i + 1) % m];
		char x4 = s[(id + 1) % n][(i + 1) % m];
		if (x1 == x2 && x3 == x4 && x1 == x4)
			ans++;
	}
	return ans;
}

int gg2(int id)
{
	int ans = 0;
	for (int i = 0; i < n; i++)
	{
		char x1 = s[i][id];
		char x2 = s[(i + 1) % n][id];
		char x3 = s[i][(id + 1) % m];
		char x4 = s[(i + 1) % n][(id + 1) % m];
		if (x1 == x2 && x3 == x4 && x1 == x4)
			ans++;
	}
	return ans;
}

int calc(int i, int j)
{
	char x1 = s[i][j];
	char x2 = s[(i + 1) % n][j];
	char x3 = s[i][(j + 1) % m];
	char x4 = s[(i + 1) % n][(j + 1) % m];
	if (x1 == x2 && x3 == x4 && x1 == x4)
		return 1;
	return 0;
}

int main()
{
	freopen("video.in", "r", stdin);
	freopen("video.out", "w", stdout);
	scanf("%d %d", &n, &m);
	for (int i = 0; i < n; i++)
		cin >> s[i];
	for (int i = 0; i < n; i++)
	{
		for (int j = 0; j < m; j++)
		{
			char x1 = s[i][j];
			char x2 = s[(i + 1) % n][j];
			char x3 = s[i][(j + 1) % m];
			char x4 = s[(i + 1) % n][(j + 1) % m];
			if (x1 == x2 && x3 == x4 && x1 == x4)
				ans++;
		}
	}
	int id1, id2;
	for (int i = 0; i < n; i++)
	{
		if (gg1(i) < ans1)
		{
			ans1 = min(ans1, gg1(i));
			id1 = i;
		}
	}
	for (int i = 0; i < m; i++)
	{
		if (gg2(i) < ans2)
		{
			ans2 = min(ans2, gg2(i));
			id2 = i;
		}
	}
	printf("%d", ans - ans1 - ans2 + calc(id1, id2));
	return 0;
}