// Author: Ivan Kazmenko (gassa@mail.ru)
// construct a chain of observations by repeatedly finding the closest one
module solution;
import std.algorithm, std.array, std.conv, std.stdio, std.string;
immutable int infinity = int.max / 2;
int dist (int [] u, int [] v)
{
int res = infinity;
foreach (i; 0..u.length)
if (u[i] && v[i] && u[i] > v[i])
res = min (res, u[i] - v[i]);
return res;
}
int solve (int n, int m, int [] [] a)
{
int [] cur = a[0];
int res = 0;
do
{
int [] next = a.minElement !(p => dist (cur, p));
int delta = dist (cur, next);
if (delta == infinity)
return -1;
res += delta;
cur = next;
}
while (cur != a[0]);
return res;
}
void main ()
{
int n, m;
readf (" %s %s", &n, &m);
readln;
int [] [] a;
foreach (k; 0..m)
a ~= readln.split.map !(x => x == "X" ? 0 : x.to!int).array;
writeln (solve (n, m, a));
}
Ly8gQXV0aG9yOiBJdmFuIEthem1lbmtvIChnYXNzYUBtYWlsLnJ1KQovLyBjb25zdHJ1Y3QgYSBjaGFpbiBvZiBvYnNlcnZhdGlvbnMgYnkgcmVwZWF0ZWRseSBmaW5kaW5nIHRoZSBjbG9zZXN0IG9uZQptb2R1bGUgc29sdXRpb247CmltcG9ydCBzdGQuYWxnb3JpdGhtLCBzdGQuYXJyYXksIHN0ZC5jb252LCBzdGQuc3RkaW8sIHN0ZC5zdHJpbmc7CgppbW11dGFibGUgaW50IGluZmluaXR5ID0gaW50Lm1heCAvIDI7CgppbnQgZGlzdCAoaW50IFtdIHUsIGludCBbXSB2KQp7CglpbnQgcmVzID0gaW5maW5pdHk7Cglmb3JlYWNoIChpOyAwLi51Lmxlbmd0aCkKCQlpZiAodVtpXSAmJiB2W2ldICYmIHVbaV0gPiB2W2ldKQoJCQlyZXMgPSBtaW4gKHJlcywgdVtpXSAtIHZbaV0pOwoJcmV0dXJuIHJlczsKfQoKaW50IHNvbHZlIChpbnQgbiwgaW50IG0sIGludCBbXSBbXSBhKQp7CglpbnQgW10gY3VyID0gYVswXTsKCWludCByZXMgPSAwOwoJZG8KCXsKCQlpbnQgW10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