/*
* Copyright (c) 2024 Emon Thakur
* All rights reserved.
*/
#include<bits/stdc++.h>
using namespace std;
int degree[2003],two=0;
bool valid(int u,int v,int lim)
{
if(degree[u]==2 || degree[v]==2) return false;
int c =0;
if(degree[u]==1) ++c;
if(degree[v]==1) ++c;
if(two + c > lim) return false;
two += c;
degree[u]++;
degree[v]++;
return true;
}
int main()
{
int n,k; cin >> n >> k;
int a[n][k];
for(int i=0;i<n;i++)
{
for(int j=0;j<k;j++) cin >> a[i][j];
}
if(n==1)
{
cout<<0<<endl;
return 0;
}
priority_queue<vector<int>>pq;
for(int i=0;i<n;i++)
{
for(int j=i+1;j<n;j++)
{
int cost = 0;
for(int m=0;m<k;m++) cost += abs(a[i][m]-a[j][m]);
pq.push({cost,i,j});
}
}
int need = n-2;
vector<int> x = pq.top();
long long ans = x[0];
pq.pop();
set<int> nodes;
nodes.insert(x[1]);
nodes.insert(x[2]);
while(nodes.size() != n)
{
x = pq.top();
pq.pop();
nodes.insert(x[1]);
nodes.insert(x[2]);
if(valid(x[1],x[2],nodes.size()-2))
{
ans += x[0];
}
else
{
nodes.erase(nodes.find(x[1]));
nodes.erase(nodes.find(x[2]));
}
}
cout << ans << endl;
}