#include <iostream>
#include <algorithm>
#include <cmath>
#include <vector>
#include <cstdio>
#include <cstdlib>
#include <numeric>
#include <set>
#include <map>
#include <string>
#include <cassert>
#include <memory.h>
#include <iomanip>

using namespace std;

#define int long long
#define sz(a) (int)(a.size())

const int MAXN = 5555;
int n, m;
int ans, cur;
int t[MAXN][MAXN];
int calcx[MAXN];
int calcy[MAXN];
int minx = 1e9, miny = 1e9;
int my, mx;

signed main()
{
	ios_base::sync_with_stdio(0), cin.tie(0);
	/*freopen("input.txt", "r", stdin);
	freopen("output.txt", "w", stdout);*/
	freopen("video.in", "r", stdin);
	freopen("video.out", "w", stdout);
	cin >> n >> m;
	cin.ignore();
	for (int i = 1; i <= n; ++i)
	{
		for (int j = 1; j <= m; ++j)
		{
			t[i][j] = cin.get() - '0';
		}
		cin.ignore();
	}
	for (int i = 1; i <= n; ++i)
	{
		for (int j = 1; j <= m; ++j)
		{
			int ii = ((i + 1) == n + 1 ? 1 : i + 1);
			int jj = ((j + 1) == m + 1 ? 1 : j + 1);
			if (t[i][j] == t[i][jj] && t[i][j] == t[ii][j] && t[i][j] == t[ii][jj])
			{
				++calcx[i];
			}
		}
		if (minx > calcx[i])
		{
			mx = i;
			minx = calcx[i];
		}
	}
	for (int j = 1; j <= m; ++j)
	{
		for (int i = 1; i <= n; ++i)
		{
			int ii = ((i + 1) == n + 1 ? 1 : i + 1);
			int jj = ((j + 1) == m + 1 ? 1 : j + 1);
			if (t[i][j] == t[i][jj] && t[i][j] == t[ii][j] && t[i][j] == t[ii][jj])
			{
				++calcy[j];
			}
		}
		if (miny > calcy[j])
		{
			my = j;
			miny = calcy[j];
		}
	}
	for (int i = 1; i <= n; ++i)
	{
		ans += calcx[i];
	}
	ans -= miny;
	ans -= minx;
	int i = mx;
	int j = my;
	int ii = ((i + 1) == n + 1 ? 1 : i + 1);
	int jj = ((j + 1) == m + 1 ? 1 : j + 1);
	if (t[i][j] == t[i][jj] && t[i][j] == t[ii][j] && t[i][j] == t[ii][jj])
	{
		++ans;
	}
	cout << ans;
	return 0;
}