#define _CRT_SECURE_NO_WARNINGS #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; #define INF (1<<29) #define rep(i,n) for(int i=0;i<(int)(n);i++) #define all(v) v.begin(),v.end() #define uniq(v) v.erase(unique(all(v)),v.end()) map> idx; vector val[200 * (2 * 100 + 2)]; int cnt[200 * (2 * 100 + 2)]; int main() { ios::sync_with_stdio(0); cin.tie(0); int n, m; cin >> n >> m; int ans = 2 * n - 1; rep(i, m) { int b = i*(2 * n + 2); val[i].reserve(n); rep(y, n)rep(x, n) { int c; cin >> c; idx[c].push_back(b + y); val[b + y].push_back(c); idx[c].push_back(b + n + x); val[b + n + x].push_back(c); if (y == x) { idx[c].push_back(b + 2 * n); val[b + 2 * n].push_back(c); } if (n - 1 - y == x) { idx[c].push_back(b + 2 * n + 1); val[b + 2 * n + 1].push_back(c); } } } rep(i, m) { rep(j, 2 * n + 2) { int ma = 0; for (int v : val[i*(2 * n + 2) + j]) { for (int k : idx[v]) { if (i*(2 * n + 2) <= k) break; ma = max(ma, ++cnt[k]); } } for (int v : val[i*(2 * n + 2) + j]) { for (int k : idx[v]) { if (i*(2 * n + 2) <= k) break; --cnt[k]; } } ans = min(ans, 2 * n - 1 - ma); } } cout << ans << endl; return 0; }