#include "bits/stdc++.h" using namespace std; #define rep(i,n) for(int (i)=0;(i)<(int)(n);++(i)) #define rer(i,l,u) for(int (i)=(int)(l);(i)<=(int)(u);++(i)) #define reu(i,l,u) for(int (i)=(int)(l);(i)<(int)(u);++(i)) static const int INF = 0x3f3f3f3f; static const long long INFL = 0x3f3f3f3f3f3f3f3fLL; typedef vector vi; typedef pair pii; typedef vector > vpii; typedef long long ll; template static void amin(T &x, U y) { if(y < x) x = y; } template static void amax(T &x, U y) { if(x < y) x = y; } int main() { int N; int M; while(~scanf("%d%d", &N, &M)) { vector> players(M); rep(k, M) { vector > C(N, vector(N)); for(int i = 0; i < N; ++ i) for(int j = 0; j < N; ++ j) scanf("%d", &C[i][j]); vector &bingos = players[k]; rep(i, N) { bingos.push_back(vi()); rep(j, N) bingos.back().push_back(C[i][j]); } rep(j, N) { bingos.push_back(vi()); rep(i, N) bingos.back().push_back(C[i][j]); } bingos.push_back(vi()); rep(i, N) bingos.back().push_back(C[i][i]); bingos.push_back(vi()); rep(i, N) bingos.back().push_back(C[i][N - 1 - i]); for(auto &v : bingos) sort(v.begin(), v.end()); } vector mark(N * N * M + 1); int ans = INF; rep(i, M) { for(const auto &v : players[i]) { for(int x : v) mark[x] = true; reu(j, i + 1, M) for(const auto &w : players[j]) { int cost = (int)w.size(); for(int x : w) cost += !mark[x]; amin(ans, cost - 1); } for(int x : v) mark[x] = false; } } printf("%d\n", ans); } return 0; }