#include <bits/stdc++.h>

using namespace std;

using ll = long long;

int main (){
	int n,d;
	cin>>n>>d;

	if(n==1){
		cout << "0\n";
		return 0;
	}

	vector<vector<ll>> pts;

	for(int i=0; i<n; i++){
		vector<ll> curr(d);
		for(int j=0; j<d; j++) cin>>curr[j];
		pts.push_back(curr);
	}


	sort(pts.begin(), pts.end());
	for(int j=0; j<d; j++){
		if(pts[0][j] > pts[1][j]){
			for(int i=0;i<n;i++) pts[i][j]*=-1;
		}
	}
	sort(pts.begin(), pts.end());

	vector<ll> dists;
	vector<vector<ll>> by_coord(d);

	for(int i=1; i<n; i++){
		ll dist=0;
		for(int j=0; j<d; j++){
			if(pts[i-1][j] > pts[i][j]){
				cout << "-1\n";
				return 0;
			}

			dist += pts[i][j] - pts[i-1][j];
		}
		
		dists.push_back(dist);
	}

	for(int i=0; i<n; i++) 
		for(int j=0; j<d; j++)
			by_coord[j].push_back(pts[i][j]);

	vector<ll> to_equal(d, 0);

	for(int j=0; j<d; j++){
		ll mid = by_coord[j][by_coord[j].size()/2];
		for(int i=0; i<n; i++){
			to_equal[j]+=abs(mid - pts[i][j]);
		}
	}

	ll total_equal = 0;
	for(int j=0; j<d; j++) total_equal+=to_equal[j];

	ll res = 1e18;

	for(int j=0; j<d; j++){
		ll val = total_equal - to_equal[j];

		int mid_ind = n/2;
		ll tg=pts[mid_ind][j];

		for(int i=mid_ind+1; i<n; i++){
			tg += dists[i-1];
			val += abs(tg - pts[i][j]);
		}
		mid_ind = n/2;
		tg=pts[mid_ind][j];

		for(int i=mid_ind-1; i>=0; i--){
			tg -= dists[i];
			val += abs(tg - pts[i][j]);
		}

		res=min(res, val);
	}

	cout<<res<<endl;
}
