#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
struct E {
int u, v, w;
bool operator<(const E &e) const { return w > e.w; }
};
struct D {
vector<int> p, r;
D(int n) : p(n), r(n, 0) { iota(p.begin(), p.end(), 0); }
int f(int x) { return p[x] == x ? x : p[x] = f(p[x]); }
bool u(int x, int y) {
x = f(x), y = f(y);
if (x == y) return false;
if (r[x] < r[y]) swap(x, y);
p[y] = x;
if (r[x] == r[y]) r[x]++;
return true;
}
};
int md(const vector<int> &a, const vector<int> &b) {
int d = 0;
for (int i = 0; i < a.size(); i++) d += abs(a[i] - b[i]);
return d;
}
ll solve(int n, int k, vector<vector<int>> &p) {
vector<E> e;
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
e.push_back({i, j, md(p[i], p[j])});
}
}
sort(e.begin(), e.end());
D dsu(n);
ll res = 0;
for (auto &x : e) {
if (dsu.u(x.u, x.v)) res += x.w;
}
return res;
}
int main() {
int n, k;
cin >> n >> k;
vector<vector<int>> p(n, vector<int>(k));
for (int i = 0; i < n; i++) {
for (int j = 0; j < k; j++) {
cin >> p[i][j];
}
}
cout << solve(n, k, p) << endl;
return 0;
}