#include <iostream>
#include <vector>
#include <algorithm>
#define repeat(i,n) for (int i = 0; (i) < (n); ++(i))
#define whole(f,x,...) ([&](decltype((x)) whole) { return (f)(begin(whole), end(whole), ## __VA_ARGS__); })(x)
using namespace std;
template <class T> void setmin(T & a, T const & b) { if (b < a) a = b; }
template <typename X, typename T> auto vectors(X x, T a) { return vector<T>(x, a); }
template <typename X, typename Y, typename Z, typename... Zs> auto vectors(X x, Y y, Z z, Zs... zs) { auto cont = vectors(y, z, zs...); return vector<decltype(cont)>(x, cont); }
int main() {
    int n, m; cin >> n >> m;
    auto c = vectors(m, n, n, int());
    repeat (i,m) repeat (y,n) repeat (x,n) cin >> c[i][y][x];
    vector<vector<vector<int> > > bingo(m);
    repeat (i,m) {
        repeat (y,n) {
            vector<int> row = c[i][y];
            whole(sort, row);
            bingo[i].push_back(row);
        }
        repeat (x,n) {
            vector<int> col(n);
            repeat (y,n) col[y] = c[i][y][x];
            whole(sort, col);
            bingo[i].push_back(col);
        }
        repeat (p,2) {
            vector<int> diag(n);
            repeat (y,n) repeat (x,n) diag[y] = c[i][y][p ? x : n-x-1];
            whole(sort, diag);
            bingo[i].push_back(diag);
        }
        whole(sort, bingo[i]);
    }
    int ans = 2*n-1;
    repeat (i,m) {
        for (auto & x : bingo[i]) {
            repeat (j,i) {
                for (auto & y : bingo[j]) {
                    auto it1 = x.begin();
                    auto it2 = y.begin();
                    int cnt = 0;
                    while (it1 != x.end() and it2 != y.end()) {
                        if (*it1 < *it2) { ++ it1; }
                        else if (*it1 > *it2) { ++ it2; }
                        else { ++ it1; ++ it2; }
                        ++ cnt;
                    }
                    while (it1 != x.end()) { ++ it1; ++ cnt; }
                    while (it2 != y.end()) { ++ it2; ++ cnt; }
                    setmin(ans, cnt-1);
                }
            }
        }
    }
    cout << ans << endl;
    return 0;
}