You are given a rectangular matrix of size $n \times m$ consisting of integers from $1$ to $2 \cdot 10^5$.

In one move, you can:  choose any element of the matrix and change its value to any integer between $1$ and $n \cdot m$, inclusive;  take any column and shift it one cell up cyclically (see the example of such cyclic shift below). 

A cyclic shift is an operation such that you choose some $j$ ($1 \le j \le m$) and set $a_{1, j} := a_{2, j}, a_{2, j} := a_{3, j}, \dots, a_{n, j} := a_{1, j}$ simultaneously. [Image] Example of cyclic shift of the first column 

You want to perform the minimum number of moves to make this matrix look like this: $\left. \begin{array}{|c c c c|} \hline 1 & {2} & {\ldots} & {m} \\{m + 1} & {m + 2} & {\ldots} & {2m} \\{\vdots} & {\vdots} & {\ddots} & {\vdots} \\{(n - 1) m + 1} & {(n - 1) m + 2} & {\ldots} & {nm} \\ \hline \end{array} \right.$ 

In other words, the goal is to obtain the matrix, where $a_{1, 1} = 1, a_{1, 2} = 2, \dots, a_{1, m} = m, a_{2, 1} = m + 1, a_{2, 2} = m + 2, \dots, a_{n, m} = n \cdot m$ (i.e. $a_{i, j} = (i - 1) \cdot m + j$) with the minimum number of moves performed.


-----Input-----

The first line of the input contains two integers $n$ and $m$ ($1 \le n, m \le 2 \cdot 10^5, n \cdot m \le 2 \cdot 10^5$) — the size of the matrix.

The next $n$ lines contain $m$ integers each. The number at the line $i$ and position $j$ is $a_{i, j}$ ($1 \le a_{i, j} \le 2 \cdot 10^5$).


-----Output-----

Print one integer — the minimum number of moves required to obtain the matrix, where $a_{1, 1} = 1, a_{1, 2} = 2, \dots, a_{1, m} = m, a_{2, 1} = m + 1, a_{2, 2} = m + 2, \dots, a_{n, m} = n \cdot m$ ($a_{i, j} = (i - 1)m + j$).


-----Examples-----
Input
3 3
3 2 1
1 2 3
4 5 6

Output
6

Input
4 3
1 2 3
4 5 6
7 8 9
10 11 12

Output
0

Input
3 4
1 6 3 4
5 10 7 8
9 2 11 12

Output
2



-----Note-----

In the first example, you can set $a_{1, 1} := 7, a_{1, 2} := 8$ and $a_{1, 3} := 9$ then shift the first, the second and the third columns cyclically, so the answer is $6$. It can be shown that you cannot achieve a better answer.

In the second example, the matrix is already good so the answer is $0$.

In the third example, it is enough to shift the second column cyclically twice to obtain a good matrix, so the answer is $2$.

Difficulty: HARD

Solutions:
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

def list2d(a, b, c):
	return [[c] * b for i in range(a)]

def list3d(a, b, c, d):
	return [[[d] * c for j in range(b)] for i in range(a)]

def list4d(a, b, c, d, e):
	return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]

def ceil(x, y=1):
	return int(-(-x // y))

def Yes():
	print('Yes')

def No():
	print('No')

def YES():
	print('YES')

def NO():
	print('NO')
INF = 10 ** 18
MOD = 10 ** 9 + 7
Ri = lambda : [int(x) for x in sys.stdin.readline().split()]
ri = lambda : sys.stdin.readline().strip()
(n, m) = Ri()
lis = []
for i in range(n):
	temp = Ri()
	temp = [i - 1 for i in temp]
	lis.append(temp)
ans = 0
for i in range(m):
	temp = 10 ** 18
	dic = {}
	for j in range(n):
		if lis[j][i] % m == i:
			if lis[j][i] // m < n:
				noshifts = (j - lis[j][i] // m) % n
				dic[noshifts] = dic.get(noshifts, 0) + 1
	for j in range(n):
		temp = min(temp, n - dic.get(j, 0) + j)
	ans += temp
print(ans)


import sys
(n, m) = map(int, input().split())
lis_2d = [[int(i) - 1 for i in input().split()] for i in range(n)]
final = 0
for j in range(m):
	count = [0] * n
	for i in range(n):
		if lis_2d[i][j] % m == j:
			pos = lis_2d[i][j] // m
			if pos < n:
				k = (i - pos + n) % n
				count[k] += 1
	ans1 = sys.maxsize
	for i in range(len(count)):
		ans = n - count[i] + i
		if ans < ans1:
			ans1 = ans
	final += ans1
print(final)


from __future__ import division, print_function
from fractions import Fraction
import sys
import os
from io import BytesIO, IOBase
from itertools import *
import bisect
from heapq import *
from math import ceil, floor
from copy import *
from collections import deque, defaultdict
from collections import Counter as counter
from itertools import combinations
from itertools import permutations as permutate
from bisect import bisect_left as bl
from operator import *
from bisect import bisect_right as br
from bisect import bisect
BUFSIZE = 8192
from sys import stderr

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')

def print(*args, **kwargs):
	(sep, file) = (kwargs.pop('sep', ' '), kwargs.pop('file', sys.stdout))
	at_start = True
	for x in args:
		if not at_start:
			file.write(sep)
		file.write(str(x))
		at_start = False
	file.write(kwargs.pop('end', '\n'))
	if kwargs.pop('flush', False):
		file.flush()
if sys.version_info[0] < 3:
	(sys.stdin, sys.stdout) = (FastIO(sys.stdin), FastIO(sys.stdout))
else:
	(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
from types import GeneratorType

def iterative(f, stack=[]):

	def wrapped_func(*args, **kwargs):
		if stack:
			return f(*args, **kwargs)
		to = f(*args, **kwargs)
		while True:
			if type(to) is GeneratorType:
				stack.append(to)
				to = next(to)
				continue
			stack.pop()
			if not stack:
				break
			to = stack[-1].send(to)
		return to
	return wrapped_func

class SortedList:

	def __init__(self, iterable=[], _load=200):
		values = sorted(iterable)
		self._len = _len = len(values)
		self._load = _load
		self._lists = _lists = [values[i:i + _load] for i in range(0, _len, _load)]
		self._list_lens = [len(_list) for _list in _lists]
		self._mins = [_list[0] for _list in _lists]
		self._fen_tree = []
		self._rebuild = True

	def _fen_build(self):
		self._fen_tree[:] = self._list_lens
		_fen_tree = self._fen_tree
		for i in range(len(_fen_tree)):
			if i | i + 1 < len(_fen_tree):
				_fen_tree[i | i + 1] += _fen_tree[i]
		self._rebuild = False

	def _fen_update(self, index, value):
		if not self._rebuild:
			_fen_tree = self._fen_tree
			while index < len(_fen_tree):
				_fen_tree[index] += value
				index |= index + 1

	def _fen_query(self, end):
		if self._rebuild:
			self._fen_build()
		_fen_tree = self._fen_tree
		x = 0
		while end:
			x += _fen_tree[end - 1]
			end &= end - 1
		return x

	def _fen_findkth(self, k):
		_list_lens = self._list_lens
		if k < _list_lens[0]:
			return (0, k)
		if k >= self._len - _list_lens[-1]:
			return (len(_list_lens) - 1, k + _list_lens[-1] - self._len)
		if self._rebuild:
			self._fen_build()
		_fen_tree = self._fen_tree
		idx = -1
		for d in reversed(range(len(_fen_tree).bit_length())):
			right_idx = idx + (1 << d)
			if right_idx < len(_fen_tree) and k >= _fen_tree[right_idx]:
				idx = right_idx
				k -= _fen_tree[idx]
		return (idx + 1, k)

	def _delete(self, pos, idx):
		_lists = self._lists
		_mins = self._mins
		_list_lens = self._list_lens
		self._len -= 1
		self._fen_update(pos, -1)
		del _lists[pos][idx]
		_list_lens[pos] -= 1
		if _list_lens[pos]:
			_mins[pos] = _lists[pos][0]
		else:
			del _lists[pos]
			del _list_lens[pos]
			del _mins[pos]
			self._rebuild = True

	def _loc_left(self, value):
		if not self._len:
			return (0, 0)
		_lists = self._lists
		_mins = self._mins
		(lo, pos) = (-1, len(_lists) - 1)
		while lo + 1 < pos:
			mi = lo + pos >> 1
			if value <= _mins[mi]:
				pos = mi
			else:
				lo = mi
		if pos and value <= _lists[pos - 1][-1]:
			pos -= 1
		_list = _lists[pos]
		(lo, idx) = (-1, len(_list))
		while lo + 1 < idx:
			mi = lo + idx >> 1
			if value <= _list[mi]:
				idx = mi
			else:
				lo = mi
		return (pos, idx)

	def _loc_right(self, value):
		if not self._len:
			return (0, 0)
		_lists = self._lists
		_mins = self._mins
		(pos, hi) = (0, len(_lists))
		while pos + 1 < hi:
			mi = pos + hi >> 1
			if value < _mins[mi]:
				hi = mi
			else:
				pos = mi
		_list = _lists[pos]
		(lo, idx) = (-1, len(_list))
		while lo + 1 < idx:
			mi = lo + idx >> 1
			if value < _list[mi]:
				idx = mi
			else:
				lo = mi
		return (pos, idx)

	def add(self, value):
		_load = self._load
		_lists = self._lists
		_mins = self._mins
		_list_lens = self._list_lens
		self._len += 1
		if _lists:
			(pos, idx) = self._loc_right(value)
			self._fen_update(pos, 1)
			_list = _lists[pos]
			_list.insert(idx, value)
			_list_lens[pos] += 1
			_mins[pos] = _list[0]
			if _load + _load < len(_list):
				_lists.insert(pos + 1, _list[_load:])
				_list_lens.insert(pos + 1, len(_list) - _load)
				_mins.insert(pos + 1, _list[_load])
				_list_lens[pos] = _load
				del _list[_load:]
				self._rebuild = True
		else:
			_lists.append([value])
			_mins.append(value)
			_list_lens.append(1)
			self._rebuild = True

	def discard(self, value):
		_lists = self._lists
		if _lists:
			(pos, idx) = self._loc_right(value)
			if idx and _lists[pos][idx - 1] == value:
				self._delete(pos, idx - 1)

	def remove(self, value):
		_len = self._len
		self.discard(value)
		if _len == self._len:
			raise ValueError('{0!r} not in list'.format(value))

	def pop(self, index=-1):
		(pos, idx) = self._fen_findkth(self._len + index if index < 0 else index)
		value = self._lists[pos][idx]
		self._delete(pos, idx)
		return value

	def bisect_left(self, value):
		(pos, idx) = self._loc_left(value)
		return self._fen_query(pos) + idx

	def bisect_right(self, value):
		(pos, idx) = self._loc_right(value)
		return self._fen_query(pos) + idx

	def count(self, value):
		return self.bisect_right(value) - self.bisect_left(value)

	def __len__(self):
		return self._len

	def __getitem__(self, index):
		(pos, idx) = self._fen_findkth(self._len + index if index < 0 else index)
		return self._lists[pos][idx]

	def __delitem__(self, index):
		(pos, idx) = self._fen_findkth(self._len + index if index < 0 else index)
		self._delete(pos, idx)

	def __contains__(self, value):
		_lists = self._lists
		if _lists:
			(pos, idx) = self._loc_left(value)
			return idx < len(_lists[pos]) and _lists[pos][idx] == value
		return False

	def __iter__(self):
		return (value for _list in self._lists for value in _list)

	def __reversed__(self):
		return (value for _list in reversed(self._lists) for value in reversed(_list))

	def __repr__(self):
		return 'SortedList({0})'.format(list(self))
mod = 1000000007

def inp():
	return sys.stdin.readline().rstrip('\r\n')

def out(var):
	sys.stdout.write(str(var))

def lis():
	return list(map(int, inp().split()))

def stringlis():
	return list(map(str, inp().split()))

def sep():
	return map(int, inp().split())

def strsep():
	return map(str, inp().split())

def fsep():
	return map(float, inp().split())

def nextline():
	out('\n')

def testcase(t):
	for p in range(t):
		solve()

def pow(x, y, p):
	res = 1
	x = x % p
	if x == 0:
		return 0
	while y > 0:
		if y & 1 == 1:
			res = res * x % p
		y = y >> 1
		x = x * x % p
	return res
from functools import reduce

def factors(n):
	return set(reduce(list.__add__, ([i, n // i] for i in range(1, int(n ** 0.5) + 1) if n % i == 0)))

def gcd(a, b):
	if a == b:
		return a
	while b > 0:
		(a, b) = (b, a % b)
	return a

def prefix_sum(ar):
	return list(accumulate(ar))

def suffix_sum(ar):
	return list(accumulate(ar[::-1]))[::-1]

def N():
	return int(inp())
dx = [0, 0, 1, -1]
dy = [1, -1, 0, 0]

def YES():
	print('YES')

def NO():
	print('NO')

def Yes():
	print('Yes')

def No():
	print('No')
from collections import defaultdict

def numberOfSetBits(i):
	i = i - (i >> 1 & 1431655765)
	i = (i & 858993459) + (i >> 2 & 858993459)
	return ((i + (i >> 4) & 252645135) * 16843009 & 4294967295) >> 24

class MergeFind:

	def __init__(self, n):
		self.parent = list(range(n))
		self.size = [1] * n
		self.num_sets = n

	def find(self, a):
		to_update = []
		while a != self.parent[a]:
			to_update.append(a)
			a = self.parent[a]
		for b in to_update:
			self.parent[b] = a
		return self.parent[a]

	def merge(self, a, b):
		a = self.find(a)
		b = self.find(b)
		if a == b:
			return
		self.num_sets -= 1
		self.parent[a] = b
		self.size[b] += self.size[a]

	def set_size(self, a):
		return self.size[self.find(a)]

	def __len__(self):
		return self.num_sets

def lcm(a, b):
	return abs(a // gcd(a, b) * b)

def solve():
	(n, m) = sep()
	ans = 0
	ar = [lis() for _ in range(n)]
	for j in range(m):
		d = defaultdict(int)
		w = 0
		t_ans = 9999999999999999
		for i in range(n):
			ar[i][j] -= 1
			if ar[i][j] % m != j:
				w += 1
				continue
			t = ar[i][j] // m
			diff = i - t
			if -n < diff < 0:
				diff += n
			d[diff] += 1
		for i in range(n):
			t = n + i - d[i]
			t_ans = min(t, t_ans)
		ans += t_ans
	print(ans)
solve()


(n, m) = (int(i) for i in input().split())
a = [[int(i) for i in input().split()] for _ in range(n)]
res = 0
for j in range(m):
	b = [0] * n
	for i in range(n):
		if a[i][j] <= n * m and (a[i][j] - j - 1) % m == 0:
			pos = (a[i][j] - j - 1) // m
			shift = i - pos if i >= pos else i - pos + n
			b[shift] += 1
	res += min((i + n - b[i] for i in range(n)))
print(res)


(n, m) = map(int, input().split())
tbl = []
for _ in range(n):
	tbl.append(list(map(int, input().split())))
l = [[k + n for k in range(n)] for _ in range(m)]
for i in range(m):
	for j in range(n):
		a = (tbl[j][i] - 1) // m
		b = (tbl[j][i] - 1) % m
		if a <= n - 1 and b == i:
			l[i][(j - a) % n] -= 1
ans = 0
for i in range(m):
	ans += min(l[i])
print(ans)


import os
import sys
import math
from io import BytesIO, IOBase
from fractions import Fraction
import collections
from itertools import permutations
from collections import defaultdict
from collections import deque
import threading
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

class SegmentTree:

	def __init__(self, data, default=0, func=lambda a, b: a + b):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __delitem__(self, idx):
		self[idx] = self._default

	def __getitem__(self, idx):
		return self.data[idx + self._size]

	def __setitem__(self, idx, value):
		idx += self._size
		self.data[idx] = value
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
			idx >>= 1

	def __len__(self):
		return self._len

	def query(self, start, stop):
		if start == stop:
			return self.__getitem__(start)
		stop += 1
		start += self._size
		stop += self._size
		res = self._default
		while start < stop:
			if start & 1:
				res = self._func(res, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res = self._func(res, self.data[stop])
			start >>= 1
			stop >>= 1
		return res

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)

class SegmentTree1:

	def __init__(self, data, default=10 ** 6, func=lambda a, b: min(a, b)):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __delitem__(self, idx):
		self[idx] = self._default

	def __getitem__(self, idx):
		return self.data[idx + self._size]

	def __setitem__(self, idx, value):
		idx += self._size
		self.data[idx] = value
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
			idx >>= 1

	def __len__(self):
		return self._len

	def query(self, start, stop):
		if start == stop:
			return self.__getitem__(start)
		stop += 1
		start += self._size
		stop += self._size
		res = self._default
		while start < stop:
			if start & 1:
				res = self._func(res, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res = self._func(res, self.data[stop])
			start >>= 1
			stop >>= 1
		return res

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)
MOD = 10 ** 9 + 7

class Factorial:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorials = [1, 1]
		self.invModulos = [0, 1]
		self.invFactorial_ = [1, 1]

	def calc(self, n):
		if n <= -1:
			print('Invalid argument to calculate n!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.factorials):
			return self.factorials[n]
		nextArr = [0] * (n + 1 - len(self.factorials))
		initialI = len(self.factorials)
		prev = self.factorials[-1]
		m = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * i % m
		self.factorials += nextArr
		return self.factorials[n]

	def inv(self, n):
		if n <= -1:
			print('Invalid argument to calculate n^(-1)')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		p = self.MOD
		pi = n % p
		if pi < len(self.invModulos):
			return self.invModulos[pi]
		nextArr = [0] * (n + 1 - len(self.invModulos))
		initialI = len(self.invModulos)
		for i in range(initialI, min(p, n + 1)):
			next = -self.invModulos[p % i] * (p // i) % p
			self.invModulos.append(next)
		return self.invModulos[pi]

	def invFactorial(self, n):
		if n <= -1:
			print('Invalid argument to calculate (n^(-1))!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.invFactorial_):
			return self.invFactorial_[n]
		self.inv(n)
		nextArr = [0] * (n + 1 - len(self.invFactorial_))
		initialI = len(self.invFactorial_)
		prev = self.invFactorial_[-1]
		p = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * self.invModulos[i % p] % p
		self.invFactorial_ += nextArr
		return self.invFactorial_[n]

class Combination:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorial = Factorial(MOD)

	def ncr(self, n, k):
		if k < 0 or n < k:
			return 0
		k = min(k, n - k)
		f = self.factorial
		return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD
mod = 10 ** 9 + 7
omod = 998244353
prime = [True for i in range(10)]
pp = [0] * 10

def SieveOfEratosthenes(n=10):
	p = 2
	c = 0
	while p * p <= n:
		if prime[p] == True:
			c += 1
			for i in range(p, n + 1, p):
				pp[i] += 1
				prime[i] = False
		p += 1

def binarySearch(arr, n, key):
	left = 0
	right = n - 1
	mid = 0
	res = arr[n - 1]
	while left <= right:
		mid = (right + left) // 2
		if arr[mid] >= key:
			res = arr[mid]
			right = mid - 1
		else:
			left = mid + 1
	return res

def binarySearch1(arr, n, key):
	left = 0
	right = n - 1
	mid = 0
	res = arr[0]
	while left <= right:
		mid = (right + left) // 2
		if arr[mid] > key:
			right = mid - 1
		else:
			res = arr[mid]
			left = mid + 1
	return res
(n, m) = map(int, input().split())
a = []
for i in range(n):
	b = list(map(int, input().split()))
	a.append(b)
res = 0
for i in range(m):
	b = [0] * n
	for j in range(n):
		num = a[j][i] - 1
		if num % m != i:
			continue
		k = num // m
		if k < n:
			if k > j:
				b[n - k + j] += 1
			else:
				b[j - k] += 1
	r = 2 * n
	for j in range(n):
		r = min(r, n - b[j] + j)
	res += r
print(res)


import os
import sys
from io import BytesIO, IOBase
from collections import Counter

def main():
	(n, m) = map(int, input().split())
	a = [list(map(int, input().split())) for _ in range(n)]
	ans = 0
	for i in range(m):
		b = Counter()
		for j in range(n):
			b[m * j + i + 1] = j + 1
		c = Counter()
		for j in range(n):
			z = b[a[j][i]]
			if z:
				c[(j - z + 1) % n] += 1
		mi = n
		for j in c:
			mi = min(mi, j + n - c[j])
		ans += mi
	print(ans)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


import sys
input = sys.stdin.buffer.readline
ans = 0
(n, m) = map(int, input().split())
a = [list(map(int, input().split())) for i in range(n)]
for j in range(m):
	mn_moves_for_row = n
	loc = {}
	for i in range(n):
		loc[i * m + j + 1] = i
	events = [0] * (n + 1)
	for i in range(n):
		if a[i][j] in loc:
			shifts = (i - loc[a[i][j]] + n) % n
			events[shifts] += 1
			events[shifts + 1] -= 1
	matches = 0
	for shifts in range(n):
		matches += events[shifts]
		mn_moves_for_row = min(mn_moves_for_row, shifts + n - matches)
	ans += mn_moves_for_row
print(ans)


import sys
input = sys.stdin.readline
(n, m) = map(int, input().split())
ans = [[0 for i in range(m)] for i in range(n)]
for i in range(n):
	q = list(map(int, input().split()))
	for j in range(len(q)):
		ans[i][j] = q[j]
col = []
maxa = 0
total = 0
from collections import *
for x in range(m):
	col = [x + 1]
	for i in range(1, n):
		col.append(col[-1] + m)
	al = defaultdict(int)
	for i in range(len(col)):
		al[col[i]] = i + 1
	dns = []
	for j in range(n):
		dns.append(ans[j][x])
	dr = defaultdict(int)
	for i in range(len(dns)):
		pos = i + 1
		value = dns[i]
		if al[value] == 0:
			continue
		if al[value] <= pos:
			dr[pos - al[value]] += 1
		else:
			dr[pos + len(dns) - al[value]] += 1
	parts = 0
	costs = 0
	maxa = 0
	for i in dr:
		maxa = max(maxa, dr[i] - i)
	total += n - maxa
print(total)


from collections import defaultdict, Counter

def main():
	(n, m) = [int(x) for x in input().split()]
	grid = [[-1] * (m + 1) for i in range(n + 1)]
	for i in range(1, n + 1):
		arr = [int(x) for x in input().split()]
		for j in range(1, m + 1):
			grid[i][j] = arr[j - 1]
	ans = 0
	for j in range(1, m + 1):
		cur_col_ans = 1000000000.0
		off_by_above = defaultdict(lambda : 0)
		off_by_below = defaultdict(lambda : 0)
		for i in range(1, n + 1):
			opt = j + (i - 1) * m
			off_by_below[grid[i][j] - opt] += 1
		for i in range(1, n + 1):
			d = m * (i - 1)
			opt = j + (i - 1) * m
			temp = i - 1
			temp += n - i + 1 - off_by_below[-d]
			temp += i - 1 - off_by_above[(n + 1 - i) * m]
			cur_col_ans = min(cur_col_ans, temp)
			off_by_below[grid[i][j] - opt] -= 1
			off_by_above[grid[i][j] - opt] += 1
		ans += cur_col_ans
	print(ans)
py2 = round(0.5)
if py2:
	from future_builtins import ascii, filter, hex, map, oct, zip
	range = xrange
import os, sys
from io import IOBase, BytesIO
BUFSIZE = 8192

class FastIO(BytesIO):
	newlines = 0

	def __init__(self, file):
		self._file = file
		self._fd = file.fileno()
		self.writable = 'x' in file.mode or 'w' in file.mode
		self.write = super(FastIO, self).write if self.writable else None

	def _fill(self):
		s = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
		self.seek((self.tell(), self.seek(0, 2), super(FastIO, self).write(s))[0])
		return s

	def read(self):
		while self._fill():
			pass
		return super(FastIO, self).read()

	def readline(self):
		while self.newlines == 0:
			s = self._fill()
			self.newlines = s.count(b'\n') + (not s)
		self.newlines -= 1
		return super(FastIO, self).readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.getvalue())
			(self.truncate(0), self.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		if py2:
			self.write = self.buffer.write
			self.read = self.buffer.read
			self.readline = self.buffer.readline
		else:
			self.write = lambda s: self.buffer.write(s.encode('ascii'))
			self.read = lambda : self.buffer.read().decode('ascii')
			self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


def push(d, x):
	if x not in d:
		d[x] = 0
	d[x] += 1

def solve(a, x, n, m):
	need = {x + i * m: i for i in range(n)}
	d = {}
	for (i, val) in enumerate(a):
		if val in need:
			push(d, (i - need[val] + n) % n)
	min_ = n
	for (move, num) in d.items():
		min_ = min(min_, move + n - num)
	return min_
(n, m) = map(int, input().split())
A = [list(map(int, input().split())) for _ in range(n)]
min_ = 0
for x in range(1, m + 1):
	a = [A[i][x - 1] for i in range(n)]
	min_ += solve(a, x, n, m)
print(min_)


import sys, math
import io, os
from collections import defaultdict as dd, deque, Counter

def data():
	return sys.stdin.readline().strip()

def mdata():
	return list(map(int, data().split()))

def outl(var):
	sys.stdout.write(' '.join(map(str, var)) + '\n')

def out(var):
	sys.stdout.write(str(var) + '\n')
mod = int(1000000000.0) + 7

def update(BIT, v, w):
	while v <= n:
		BIT[v] += w
		v += v & -v

def getvalue(BIT, v):
	ANS = 0
	while v != 0:
		ANS += BIT[v]
		v -= v & -v
	return ANS

def bisect_on_BIT(BIT, x):
	if x <= 0:
		return 0
	ANS = 0
	h = 1 << n - 1
	while h > 0:
		if ANS + h <= n and BIT[ANS + h] < x:
			x -= BIT[ANS + h]
			ANS += h
		h //= 2
	return ANS + 1
(n, m) = mdata()
a = [mdata() for i in range(n)]
ans = 0
for i in range(m):
	d = dd(int)
	for j in range(n):
		if (a[j][i] - 1) % m == i and (a[j][i] - 1) // m < n:
			d[(j - (a[j][i] - 1) // m) % n] += 1
	min1 = n
	for j in d:
		min1 = min(min1, j + n - d[j])
	ans += min1
out(ans)


import sys
input = sys.stdin.readline
(n, m) = map(int, input().split())
CR = [list(map(int, input().split())) for i in range(n)]
for i in range(n):
	for j in range(m):
		CR[i][j] -= 1
MAX = n * m
ANS = 0
for i in range(m):
	SCORE = [0] * n
	for j in range(n):
		if CR[j][i] % m == i % m and 0 <= CR[j][i] < MAX:
			x = (CR[j][i] - i % m) // m
			SCORE[(j - x) % n] += 1
	ANS += min([n + j - SCORE[j] for j in range(n)])
print(ANS)


from collections import defaultdict

def solve():
	(n, m) = map(int, input().split())
	l = [list(map(int, input().split())) for i in range(n)]
	for i in range(n):
		for j in range(m):
			l[i][j] -= 1
	ans = 0
	for i in range(m):
		d = defaultdict(int)
		for j in range(n):
			if l[j][i] % m == i and l[j][i] < n * m:
				d[(j + n - l[j][i] // m) % n] += 1
		mn = n
		for p in d.items():
			if p[0] + (n - p[1]) < mn:
				mn = p[0] + (n - p[1])
		ans += mn
	print(ans)
solve()


(n, m) = tuple(map(int, input().split()))
arr = [list(map(int, input().split())) for _ in range(n)]

def getMinMoves(arr, n, m):
	moves = 0
	for j in range(m):
		cnts = [0] * n
		biggest = (n - 1) * m + j
		for i in range(n):
			if (arr[i][j] - 1) % m == j and arr[i][j] - 1 <= biggest:
				pos = (arr[i][j] - 1 - j) // m
				if pos > i:
					cnts[n - pos + i] += 1
				else:
					cnts[i - pos] += 1
		min_moves = float('inf')
		for shft in range(n):
			match_cnt = cnts[shft]
			min_moves = min(min_moves, shft + n - match_cnt)
		moves += min_moves
	return moves
print(getMinMoves(arr, n, m))


import math, collections, sys
input = sys.stdin.readline
(n, m) = map(int, input().split())
a = []
for i in range(n):
	a.append(list(map(int, input().split())))
z = [[n for i in range(m)] for i in range(n)]
for j in range(m):
	for i in range(n):
		num = a[i][j]
		if num > (n - 1) * m + j + 1 or num % m != (j + 1) % m:
			continue
		num -= j + 1
		row = num // m
		shift = (i - row + n) % n
		z[shift][j] -= 1
ans = 0
for j in range(m):
	m = 2 * 10 ** 6
	for i in range(n):
		m = min(m, z[i][j] + i)
	ans += m
print(ans)


(n, m) = map(int, input().split())

def solve(actual, target):
	rots = {i: 0 for i in range(n)}
	for (i, x) in enumerate(actual):
		if x in target:
			rots[(i - target[x]) % n] -= 1
	return min([n + i + rots[i] for i in range(n)])
a = []
for _ in range(n):
	b = [int(x) for x in input().split()]
	a.append(b)
for i in range(n):
	for j in range(m):
		a[i][j] -= 1
ans = 0
for j in range(m):
	target = {m * i + j: i for i in range(n)}
	actual = [a[i][j] for i in range(n)]
	ans += solve(actual, target)
print(ans)


from sys import stdin
(n, m) = [int(x) for x in stdin.readline().split()]
grid = []
for r in range(n):
	grid.append([int(x) - 1 for x in stdin.readline().split()])
grid2 = [[grid[x][y] for x in range(n)] for y in range(m)]
total = 0
for (ind, x) in enumerate(grid2):
	counts = {}
	for (pos, y) in enumerate(x):
		if y % m == ind and y < n * m:
			endpos = y // m
			if (pos - endpos) % n in counts:
				counts[(pos - endpos) % n] += 1
			else:
				counts[(pos - endpos) % n] = 1
	low = n
	for x in counts:
		low = min(low, x + n - counts[x])
	total += low
print(total)


(n, m) = list(map(int, input().split()))
lista = []
for i in range(n):
	arr = list(map(int, input().split()))
	lista.append(arr)
answer = 0
for i in range(m):
	dica = {}
	for j in range(n):
		dica[i + 1 + m * j] = j
	dicb = {}
	for j in range(n):
		dicb[j] = 0
	for j in range(n):
		if lista[j][i] in dica:
			index = (j - dica[lista[j][i]] + n) % n
			dicb[index] += 1
	ans = n
	for i in range(n):
		if dicb[i] > 0:
			ans = min(ans, i + n - dicb[i])
	answer = answer + ans
print(answer)


import os
import sys
from math import *
from collections import *
from bisect import *
from io import BytesIO, IOBase

def vsInput():
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
ALPHA = 'abcdefghijklmnopqrstuvwxyz'
M = 1000000007
EPS = 1e-06

def Ceil(a, b):
	return a // b + int(a % b > 0)

def value():
	return tuple(map(int, input().split()))

def array():
	return [int(i) for i in input().split()]

def Int():
	return int(input())

def Str():
	return input()

def arrayS():
	return [i for i in input().split()]
(r, c) = value()
a = []
for i in range(r):
	a.append(array())
b = [[0 for j in range(r)] for i in range(c)]
for i in range(c):
	for j in range(r):
		b[i][j] = a[j][i]
a = b[:]
(r, c) = (c, r)
ans = 0
for i in range(r):
	need = []
	ind = defaultdict(int)
	shifts_made = c
	for j in range(c):
		need.append(j * r + i + 1)
		ind[j * r + i + 1] = j
	C = Counter(need)
	shifts = defaultdict(int)
	for j in range(c):
		if a[i][j] in C:
			shifts[(j - ind[a[i][j]] + c) % c] += 1
	for j in shifts:
		shifts_made = min(shifts_made, j + c - shifts[j])
	ans += shifts_made
print(ans)


from sys import stdin

def solve():
	(n, m) = map(int, stdin.readline().split())
	l = [list(map(lambda x: int(x) - 1, stdin.readline().split())) for i in range(n)]
	mvs = 0
	for j in range(m):
		d = {}
		ans = n
		for i in range(n):
			if l[i][j] % m == j and l[i][j] < n * m:
				idx = (l[i][j] - j) // m
				if i - idx >= 0:
					x = i - idx
				else:
					x = n + i - idx
				d.setdefault(x, 0)
				d[x] += 1
		for k in d:
			ans = min(ans, k + n - d[k])
		mvs += ans
	print(mvs)
solve()


import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

def RL():
	return map(int, sys.stdin.readline().rstrip().split())

def RLL():
	return list(map(int, sys.stdin.readline().rstrip().split()))

def N():
	return int(input())

def comb(n, m):
	return factorial(n) / (factorial(m) * factorial(n - m)) if n >= m else 0

def perm(n, m):
	return factorial(n) // factorial(n - m) if n >= m else 0

def mdis(x1, y1, x2, y2):
	return abs(x1 - x2) + abs(y1 - y2)
mod = 998244353
INF = float('inf')
from math import factorial
from collections import Counter, defaultdict, deque
from heapq import heapify, heappop, heappush

def main():
	(n, m) = RL()
	arr = [RLL() for _ in range(n)]
	res = 0
	for i in range(m):
		fir = i + 1
		rec = defaultdict(int)
		for j in range(n):
			now = arr[j][i]
			if (now - fir) % m != 0 or now > n * m:
				continue
			p = (now - fir) // m
			if j - p >= 0:
				rec[j - p] += 1
			else:
				rec[n - (p - j)] += 1
		tres = n
		for (k, v) in rec.items():
			if k >= 0:
				tres = min(tres, n - v + k)
		res += tres
	print(res)
main()


(n, m) = map(int, input().split())
a = [list(map(lambda x: x - 1, map(int, input().split()))) for _ in range(n)]
ans = 0
for j in range(m):
	tmp = [0 for _ in range(n)]
	for i in range(n):
		if a[i][j] % m == j:
			pos = a[i][j] // m
			if pos < n:
				tmp[(i - pos + n) % n] += 1
	cur = n - tmp[0]
	for i in range(1, n):
		cur = min(cur, n - tmp[i] + i)
	ans += cur
print(ans)


import sys
input = sys.stdin.readline
from collections import *
(n, m) = map(int, input().split())
a = [list(map(int, input().split())) for _ in range(n)]
ans = 0
for i in range(m):
	l = [i + 1]
	for _ in range(n - 1):
		l.append(l[-1] + m)
	s = set(l)
	idx = defaultdict(int)
	for j in range(n):
		idx[l[j]] = j
	cnt = [n] * n
	for j in range(n):
		if a[j][i] in s:
			move = (j - idx[a[j][i]]) % n
			cnt[move] -= 1
	mi = 10 ** 18
	for j in range(n):
		mi = min(mi, j + cnt[j])
	ans += mi
print(ans)


import sys
import math
from collections import defaultdict, deque
import heapq
(n, m) = map(int, sys.stdin.readline().split())
arr = []
for i in range(n):
	l = list(map(int, sys.stdin.readline().split()))
	arr.append(l)
ans = 0
for i in range(m):
	dic = defaultdict(int)
	cnt = 0
	vis = defaultdict(int)
	for j in range(n):
		x = arr[j][i]
		if (x - (i + 1)) % m == 0:
			vis[x] = 1
			y = (x - (i + 1)) // m
			if j >= y:
				delta = j - y
			else:
				delta = j + (n - y)
			if delta > n or delta < 0 or x < 1 or (x > n * m):
				cnt += 1
				continue
			dic[delta] += 1
		else:
			cnt += 1
	ch = n
	for j in dic:
		change = min(j + n - dic[j], n)
		ch = min(ch, change)
	ans = ans + ch
print(ans)


import sys
import io, os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
(n, m) = map(int, input().split())
mat = [[] for _ in range(m)]
for i in range(n):
	row = [int(i) for i in input().split()]
	for j in range(m):
		mat[j].append(row[j] - 1)
ans = 0
maxa = n * m
for i in range(m):
	score = [0] * n
	for j in range(n):
		if mat[i][j] % m == i % m and 0 <= mat[i][j] < maxa:
			ind = int((mat[i][j] - i % m) // m)
			score[(j - ind) % n] += 1
	mina = 10000000000
	for i in range(len(score)):
		mina = min(mina, i + n - score[i])
	ans += mina
sys.stdout.write(str(int(ans)) + '\n')


def ans(col, act, n, m, colnum):
	indices = []
	reqIndices = []
	useful = []
	for i in range(n):
		if col[i] % m == act[0] % m and col[i] <= m * n:
			indices += [i]
			useful += [col[i]]
			reqIndices += [(col[i] - colnum) // m]
	d = {}
	for i in range(len(indices)):
		try:
			d[(indices[i] - reqIndices[i]) % n] += 1
		except:
			d[(indices[i] - reqIndices[i]) % n] = 1
	mn = 1000000000000000000
	for i in d:
		moves = i + (n - d[i])
		mn = min(mn, moves)
	return min(mn, n)
(n, m) = map(int, input().split())
x = [list(map(int, input().split())) for i in range(n)]
colwise = [[x[j][i] for j in range(n)] for i in range(m)]
actual = [[i + (j - 1) * m for j in range(1, n + 1)] for i in range(1, m + 1)]
movs = 0
for i in range(m):
	movs += ans(colwise[i], actual[i], n, m, i + 1)
print(movs)


import sys
(n, m) = map(int, input().split())
summ = 0
a = [list(map(int, sys.stdin.readline().split())) for _ in range(n)]
for i in range(m):
	col = [a[j][i] - j * m - i - 1 for j in range(n)]
	cnt = [n + j for j in range(n)]
	for j in range(len(col)):
		if col[j] % m == 0 and -j <= col[j] // m < n - j:
			cnt[(n - col[j] // m % n) % n] -= 1
	summ += min(cnt)
print(summ)


from math import ceil
import sys
input = sys.stdin.readline
(n, m) = map(int, input().split())
z = n * m
a = []
for i in range(m):
	a.append([])
for i in range(n):
	inp = [int(i) for i in input().split()]
	for i in range(len(inp)):
		a[i].append(inp[i])
ar = [0] * n
ans = 0
for i in range(m):
	minn = 1000000
	for j in range(n):
		if a[i][j] % m == (i + 1) % m and a[i][j] <= n * m:
			ar[j - ceil(a[i][j] / m) + 1] += 1
	for k in range(len(ar)):
		minn = min(minn, k + (n - ar[k]))
		ar[k] = 0
	ans += minn
print(ans)


(n, m) = map(int, input().split())
g = []
for i in range(n):
	c = list(map(int, input().split()))
	g.append(c)
count = 0
(pos, shift) = (0, 0)
for i in range(m):
	b = [0] * n
	for j in range(n):
		if g[j][i] <= n * m and (g[j][i] - 1 - i) % m == 0:
			pos = (g[j][i] - 1 - i) // m
			shift = (j - pos + n) % n
			b[shift] += 1
	mini = n
	for k in range(n):
		mini = min(mini, n - b[k] + k)
	count += mini
print(count)


from sys import stdin
from _collections import deque
mod = 10 ** 9 + 7
import sys
sys.setrecursionlimit(10 ** 5)
from queue import PriorityQueue
from bisect import bisect_right
from bisect import bisect_left
from collections import defaultdict
from math import sqrt, factorial, gcd, log2, inf, ceil
import heapq
input = lambda : sys.stdin.readline().rstrip()
from sys import stdin, stdout
from heapq import heapify, heappush, heappop
(n, m) = map(int, input().split())
la = []
ans = []
for i in range(n):
	k = list(map(int, input().split()))
	la.append(k)
	ka = [0] * m
	ans.append(ka)
for i in range(m):
	for j in range(n):
		ans[j][i] += i + 1 + j * m
fin = 0
for i in range(m):
	mini = n
	hash = defaultdict(int)
	posn = defaultdict(int)
	for j in range(n):
		z = ans[j][i]
		posn[z] = j
	for j in range(n):
		z = ans[j][i]
		z1 = la[j][i]
		if 0 < z <= n * m and z1 in posn:
			p = posn[z1]
			shift = (j - p) % n
			hash[shift] += 1
	for i in hash:
		z = hash[i]
		mini = min(n - z + i, mini)
	fin += mini
print(fin)


import math
import heapq, bisect
import sys
from collections import deque, defaultdict
from fractions import Fraction
mod = 10 ** 9 + 7
mod1 = 998244353
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

class TreeNode:

	def __init__(self, k, v):
		self.key = k
		self.value = v
		self.left = None
		self.right = None
		self.parent = None
		self.height = 1
		self.num_left = 1
		self.num_total = 1

class AvlTree:

	def __init__(self):
		self._tree = None

	def add(self, k, v):
		if not self._tree:
			self._tree = TreeNode(k, v)
			return
		node = self._add(k, v)
		if node:
			self._rebalance(node)

	def _add(self, k, v):
		node = self._tree
		while node:
			if k < node.key:
				if node.left:
					node = node.left
				else:
					node.left = TreeNode(k, v)
					node.left.parent = node
					return node.left
			elif node.key < k:
				if node.right:
					node = node.right
				else:
					node.right = TreeNode(k, v)
					node.right.parent = node
					return node.right
			else:
				node.value = v
				return

	@staticmethod
	def get_height(x):
		return x.height if x else 0

	@staticmethod
	def get_num_total(x):
		return x.num_total if x else 0

	def _rebalance(self, node):
		n = node
		while n:
			lh = self.get_height(n.left)
			rh = self.get_height(n.right)
			n.height = max(lh, rh) + 1
			balance_factor = lh - rh
			n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right)
			n.num_left = 1 + self.get_num_total(n.left)
			if balance_factor > 1:
				if self.get_height(n.left.left) < self.get_height(n.left.right):
					self._rotate_left(n.left)
				self._rotate_right(n)
			elif balance_factor < -1:
				if self.get_height(n.right.right) < self.get_height(n.right.left):
					self._rotate_right(n.right)
				self._rotate_left(n)
			else:
				n = n.parent

	def _remove_one(self, node):
		replacement = node.left or node.right
		if node.parent:
			if AvlTree._is_left(node):
				node.parent.left = replacement
			else:
				node.parent.right = replacement
			replacement.parent = node.parent
			node.parent = None
		else:
			self._tree = replacement
			replacement.parent = None
		node.left = None
		node.right = None
		node.parent = None
		self._rebalance(replacement)

	def _remove_leaf(self, node):
		if node.parent:
			if AvlTree._is_left(node):
				node.parent.left = None
			else:
				node.parent.right = None
			self._rebalance(node.parent)
		else:
			self._tree = None
		node.parent = None
		node.left = None
		node.right = None

	def remove(self, k):
		node = self._get_node(k)
		if not node:
			return
		if AvlTree._is_leaf(node):
			self._remove_leaf(node)
			return
		if node.left and node.right:
			nxt = AvlTree._get_next(node)
			node.key = nxt.key
			node.value = nxt.value
			if self._is_leaf(nxt):
				self._remove_leaf(nxt)
			else:
				self._remove_one(nxt)
			self._rebalance(node)
		else:
			self._remove_one(node)

	def get(self, k):
		node = self._get_node(k)
		return node.value if node else -1

	def _get_node(self, k):
		if not self._tree:
			return None
		node = self._tree
		while node:
			if k < node.key:
				node = node.left
			elif node.key < k:
				node = node.right
			else:
				return node
		return None

	def get_at(self, pos):
		x = pos + 1
		node = self._tree
		while node:
			if x < node.num_left:
				node = node.left
			elif node.num_left < x:
				x -= node.num_left
				node = node.right
			else:
				return (node.key, node.value)
		raise IndexError('Out of ranges')

	@staticmethod
	def _is_left(node):
		return node.parent.left and node.parent.left == node

	@staticmethod
	def _is_leaf(node):
		return node.left is None and node.right is None

	def _rotate_right(self, node):
		if not node.parent:
			self._tree = node.left
			node.left.parent = None
		elif AvlTree._is_left(node):
			node.parent.left = node.left
			node.left.parent = node.parent
		else:
			node.parent.right = node.left
			node.left.parent = node.parent
		bk = node.left.right
		node.left.right = node
		node.parent = node.left
		node.left = bk
		if bk:
			bk.parent = node
		node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
		node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
		node.num_left = 1 + self.get_num_total(node.left)

	def _rotate_left(self, node):
		if not node.parent:
			self._tree = node.right
			node.right.parent = None
		elif AvlTree._is_left(node):
			node.parent.left = node.right
			node.right.parent = node.parent
		else:
			node.parent.right = node.right
			node.right.parent = node.parent
		bk = node.right.left
		node.right.left = node
		node.parent = node.right
		node.right = bk
		if bk:
			bk.parent = node
		node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
		node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
		node.num_left = 1 + self.get_num_total(node.left)

	@staticmethod
	def _get_next(node):
		if not node.right:
			return node.parent
		n = node.right
		while n.left:
			n = n.left
		return n

class SegmentTree1:

	def __init__(self, data, default='z', func=lambda a, b: min(a, b)):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __delitem__(self, idx):
		self[idx] = self._default

	def __getitem__(self, idx):
		return self.data[idx + self._size]

	def __setitem__(self, idx, value):
		idx += self._size
		self.data[idx] = value
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
			idx >>= 1

	def __len__(self):
		return self._len

	def query(self, start, stop):
		if start == stop:
			return self.__getitem__(start)
		stop += 1
		start += self._size
		stop += self._size
		res = self._default
		while start < stop:
			if start & 1:
				res = self._func(res, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res = self._func(res, self.data[stop])
			start >>= 1
			stop >>= 1
		return res

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)

class SegmentTree:

	def __init__(self, data, default=0, func=lambda a, b: a + b):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __delitem__(self, idx):
		self[idx] = self._default

	def __getitem__(self, idx):
		return self.data[idx + self._size]

	def __setitem__(self, idx, value):
		idx += self._size
		self.data[idx] = value
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
			idx >>= 1

	def __len__(self):
		return self._len

	def query(self, start, stop):
		if start == stop:
			return self.__getitem__(start)
		stop += 1
		start += self._size
		stop += self._size
		res = self._default
		while start < stop:
			if start & 1:
				res = self._func(res, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res = self._func(res, self.data[stop])
			start >>= 1
			stop >>= 1
		return res

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)

class Factorial:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorials = [1, 1]
		self.invModulos = [0, 1]
		self.invFactorial_ = [1, 1]

	def calc(self, n):
		if n <= -1:
			print('Invalid argument to calculate n!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.factorials):
			return self.factorials[n]
		nextArr = [0] * (n + 1 - len(self.factorials))
		initialI = len(self.factorials)
		prev = self.factorials[-1]
		m = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * i % m
		self.factorials += nextArr
		return self.factorials[n]

	def inv(self, n):
		if n <= -1:
			print('Invalid argument to calculate n^(-1)')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		p = self.MOD
		pi = n % p
		if pi < len(self.invModulos):
			return self.invModulos[pi]
		nextArr = [0] * (n + 1 - len(self.invModulos))
		initialI = len(self.invModulos)
		for i in range(initialI, min(p, n + 1)):
			next = -self.invModulos[p % i] * (p // i) % p
			self.invModulos.append(next)
		return self.invModulos[pi]

	def invFactorial(self, n):
		if n <= -1:
			print('Invalid argument to calculate (n^(-1))!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.invFactorial_):
			return self.invFactorial_[n]
		self.inv(n)
		nextArr = [0] * (n + 1 - len(self.invFactorial_))
		initialI = len(self.invFactorial_)
		prev = self.invFactorial_[-1]
		p = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * self.invModulos[i % p] % p
		self.invFactorial_ += nextArr
		return self.invFactorial_[n]

class Combination:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorial = Factorial(MOD)

	def ncr(self, n, k):
		if k < 0 or n < k:
			return 0
		k = min(k, n - k)
		f = self.factorial
		return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD

def powm(a, n, m):
	if a == 1 or n == 0:
		return 1
	if n % 2 == 0:
		s = powm(a, n // 2, m)
		return s * s % m
	else:
		return a * powm(a, n - 1, m) % m

def sort_list(list1, list2):
	zipped_pairs = zip(list2, list1)
	z = [x for (_, x) in sorted(zipped_pairs)]
	return z

def product(l):
	por = 1
	for i in range(len(l)):
		por *= l[i]
	return por

def binarySearchCount(arr, n, key):
	left = 0
	right = n - 1
	count = 0
	while left <= right:
		mid = int((right + left) / 2)
		if arr[mid] <= key:
			count = mid + 1
			left = mid + 1
		else:
			right = mid - 1
	return count

def countdig(n):
	c = 0
	while n > 0:
		n //= 10
		c += 1
	return c

def countGreater(arr, n, k):
	l = 0
	r = n - 1
	leftGreater = n
	while l <= r:
		m = int(l + (r - l) / 2)
		if arr[m] >= k:
			leftGreater = m
			r = m - 1
		else:
			l = m + 1
	return n - leftGreater
(n, k) = map(int, input().split())
m = k
a = []
ans = 0
ind = [defaultdict(int) for i in range(k)]
r = [0 for i in range(k)]
unset = [0 for i in range(k)]
for i in range(n):
	a.append(list(map(int, input().split())))
for i in range(n):
	for j in range(k):
		if a[i][j] % m != (j + 1) % k or a[i][j] > n * m:
			r[j] += 1
			ans += 1
		else:
			t = (a[i][j] - 1) // m
			if i != t:
				unset[j] += 1
			ind[j][(i - t) % n] += 1
for i in range(k):
	t = unset[i]
	for j in ind[i]:
		if j < 0:
			continue
		shi = ind[i][j]
		t = min(t, n - r[i] - shi + j)
	ans += t
print(ans)


import sys
from collections import Counter
(n, m) = map(int, input().split())
a = [list(map(int, l.split())) for l in sys.stdin]
ans = 0
for x in range(m):
	if n == 1:
		if a[0][x] != x + 1:
			ans += 1
		continue
	cnt = Counter()
	for y in range(n):
		if a[y][x] <= n * m and a[y][x] % m == (x + 1) % m:
			dy = (a[y][x] - x - 1) // m
			cnt[y - dy + (n if y < dy else 0)] += 1
	cost = n
	for (k, v) in cnt.items():
		cost = min(cost, k + (n - v))
	ans += cost
print(ans)


(n, m) = map(int, input().split())
ls = [list(map(int, input().split())) for i in range(n)]
ans = 0
for i in range(m):
	minop = n
	mls = [0] * n
	for j in range(n):
		if ls[j][i] % m == (i + 1) % m:
			target = ls[j][i] // m
			if i == m - 1:
				target -= 1
			if target >= n:
				continue
			if j >= target:
				shift = j - target
			else:
				shift = n - (target - j)
			mls[shift] += 1
	for j in range(n):
		minop = min(minop, j + n - mls[j])
	ans += minop
print(ans)


import sys
reader = (line.rstrip() for line in sys.stdin)
input = reader.__next__
(n, m) = map(int, input().split())
cols = [[] for j in range(m)]
for i in range(n):
	row = map(int, input().split())
	for (j, a) in enumerate(row):
		cols[j].append(a - 1)
total = 0
for j in range(m):
	cnt = [0] * n
	for (i, a) in enumerate(cols[j]):
		if a % m != j:
			continue
		pos = a // m
		if pos < n:
			cnt[(i - pos + n) % n] += 1
	minOps = float('inf')
	for (i, ci) in enumerate(cnt):
		minOps = min(minOps, n - ci + i)
	total += minOps
print(total)


from math import log2
(n, m) = map(int, input().split())
g = []
for i in range(n):
	ls = list(map(int, input().split()))
	g.append(ls)
res = 0
for j in range(m):
	b = [0] * n
	for i in range(n):
		if g[i][j] <= n * m and (g[i][j] - 1 - j) % m == 0:
			pos = (g[i][j] - 1 - j) // m
			shift = (i - pos + n) % n
			b[shift] += 1
	var = n
	for i in range(n):
		var = min(var, i + n - b[i])
	res += var
print(res)


import sys
input = sys.stdin.readline
(n, m) = map(int, input().split())
a = [list(map(int, input().split())) for i in range(n)]
ans = 0
for j in range(m):
	idx = {}
	for i in range(n):
		idx[i * m + (j + 1)] = i
	score_cyc = 10 ** 18
	r = 0
	cyc = [0] * n
	for i in range(n):
		if a[i][j] not in idx:
			r += 1
		else:
			dist = i - idx[a[i][j]] if idx[a[i][j]] <= i else n + i - idx[a[i][j]]
			cyc[dist % n] += 1
	for i in range(n):
		score_cyc = min(score_cyc, i + (n - cyc[i] - r) + r)
	ans += score_cyc
print(ans)


import sys
from collections import defaultdict
import math
from math import ceil, log2
import os
import sys
from io import BytesIO, IOBase
from collections import defaultdict
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
t = 1
for _ in range(t):
	(n, m) = map(int, input().split())
	b = []
	for j in range(n):
		b.append(list(map(int, input().split())))
	ans = 0
	for j in range(m):
		val = [0] * n
		mi = j + 1
		ma = (n - 1) * m + mi
		for i in range(n):
			if b[i][j] >= mi and b[i][j] <= ma and ((b[i][j] - mi) % m == 0):
				pos = (b[i][j] - mi) // m
				if pos <= i:
					val[i - pos] += 1
				else:
					val[i + n - pos] += 1
		ma = n
		for i in range(n):
			ma = min(ma, i + n - val[i])
		ans += ma
	print(ans)


import sys
from sys import stdin
(n, m) = map(int, stdin.readline().split())
a = [list(map(int, stdin.readline().split())) for i in range(n)]
for i in range(n):
	for j in range(m):
		a[i][j] -= 1
ans = 0
for j in range(m):
	lis = [0] * n
	for i in range(n):
		if a[i][j] % m == j and 0 <= a[i][j] < n * m:
			cy = (i - a[i][j] // m) % n
			lis[cy] += 1
	nans = n
	for i in range(n):
		nans = min(nans, i + n - lis[i])
	ans += nans
print(ans)


from collections import defaultdict
(n, m) = map(int, input().split())
data = [[] for _ in range(m)]
for i in range(n):
	a = list(map(int, input().split()))
	for (j, x) in enumerate(a):
		data[j].append(x)
ans = 0
for j in range(m):
	ideal = defaultdict(int)
	for i in range(n):
		ideal[i * m + j + 1] = i
	cir = [0 for _ in range(n)]
	for i in range(n):
		if data[j][i] in ideal:
			need = (n + i - ideal[data[j][i]]) % n
			cir[need] += 1
	res = n
	for i in range(n):
		tmp = i + (n - cir[i])
		res = min(tmp, res)
	ans += res
print(ans)


from sys import stdin, stdout

def main():
	arr = list(map(int, stdin.readline().split()))
	X = arr[0]
	Y = arr[1]
	rect = list()
	temp = list()
	for j in range(X):
		temp.append(0)
	for i in range(Y):
		rect.append(list(temp))
	for i in range(X):
		arr = list(map(int, stdin.readline().split()))
		for j in range(Y):
			if (arr[j] - j - 1) % Y != 0 or arr[j] > X * Y:
				continue
			sure = int((arr[j] - j - 1) / Y)
			sure = i - sure
			if sure < 0:
				sure += X
			rect[j][sure] += 1
	total_sum = 0
	for i in range(Y):
		maxer = X
		for j in range(X):
			count = X - rect[i][j] + j
			if count < maxer:
				maxer = count
		total_sum += maxer
	stdout.write(str(total_sum))
main()


import sys
import math
from collections import defaultdict, Counter
input = sys.stdin.readline

def print(x):
	sys.stdout.write(str(x) + '\n')
(n, m) = map(int, input().split())
ans = 0
l1 = defaultdict(dict)
for i in range(n):
	a = list(map(int, input().split()))
	for j in range(m):
		if (a[j] - 1) % m == j and a[j] <= n * m:
			d = (a[j] - 1) // m
			a[j] = i - d
			if a[j] < 0:
				a[j] += n
			s = l1[j].setdefault(a[j], 0)
			l1[j][a[j]] += 1
		else:
			a[j] = -1
for j in range(m):
	amt = n
	for k in l1[j]:
		amt = min(amt, k + n - l1[j][k])
	ans += amt
print(ans)


import sys, math, itertools
from collections import Counter, deque, defaultdict
from bisect import bisect_left, bisect_right
from heapq import heappop, heappush, heapify, nlargest
from copy import deepcopy
mod = 10 ** 9 + 7
INF = float('inf')

def inp():
	return int(sys.stdin.readline())

def inpl():
	return list(map(int, sys.stdin.readline().split()))

def inpl_1():
	return list(map(lambda x: int(x) - 1, sys.stdin.readline().split()))

def inps():
	return sys.stdin.readline()

def inpsl(x):
	tmp = sys.stdin.readline()
	return list(tmp[:x])

def err(x):
	print(x)
	exit()
(n, m) = inpl()
mt = [inpl_1() for _ in range(n)]
res = 0
if n == 1 and m == 1:
	print(0 if mt[0][0] == 0 else 1)
	exit()
for j in range(m):
	ans = n
	d = [0] * n
	for i in range(n):
		if mt[i][j] % m == j:
			r = mt[i][j] // m
			if r >= n:
				continue
			up = i - r if i - r >= 0 else n - (r - i)
			d[up] += 1
	for (i, x) in enumerate(d):
		cost = i + n - x
		if cost < ans:
			ans = cost
	res += ans
print(res)


from sys import stdin as rl
(n, m) = [int(i) for i in rl.readline().split()]
arr = []
ans = n * m
for i in range(n):
	arr.append([int(i) for i in rl.readline().split()])
for i in range(m):
	cnt = [0 for i in range(n)]
	for j in range(n):
		ele = arr[j][i]
		if ele <= n * m:
			if ele % m == (i + 1) % m:
				row = int((ele - i - 1) // m)
				cnt[(j - row) % n] += 1
	pa = 0
	for k in range(n):
		if cnt[k] - k > pa:
			pa = cnt[k] - k
	ans -= pa
print(ans)


import io
import os
from collections import Counter, defaultdict, deque

def solve(R, C, grid):

	def moveUpDist(i, j):
		if i >= j:
			return i - j
		return R - (j - i)
	ans = 0
	for c in range(C):
		targets = {r * C + c + 1: r for r in range(R)}
		matches = Counter()
		for r in range(R):
			if grid[r][c] in targets:
				matches[moveUpDist(r, targets[grid[r][c]])] += 1
		best = R
		for (rotateCost, savings) in matches.items():
			best = min(best, rotateCost + (R - savings))
		ans += best
	return ans
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
(N, M) = [int(x) for x in input().split()]
grid = [[int(x) for x in input().split()] for r in range(N)]
ans = solve(N, M, grid)
print(ans)


(n, m) = map(int, input().split())
mtx = []
for _ in range(n):
	mtx.append(list(map(int, input().split())))
total = 0
for i in range(m):
	cnt = {}
	for j in range(n):
		if (mtx[j][i] - i - 1) % m == 0:
			pos = (mtx[j][i] - 1) // m
			if pos < n:
				c = (j - pos) % n
				cnt[c] = cnt.get(c, 0) + 1
	add = n
	for (k, v) in cnt.items():
		add = min(add, k + n - v)
	total += add
print(total)


from collections import defaultdict
import sys, math
f = None
try:
	f = open('q1.input', 'r')
except IOError:
	f = sys.stdin
if 'xrange' in dir(__builtins__):
	range = xrange
sys.setrecursionlimit(10 ** 6)

def print_case_iterable(case_num, iterable):
	print('Case #{}: {}'.format(case_num, ' '.join(map(str, iterable))))

def print_case_number(case_num, iterable):
	print('Case #{}: {}'.format(case_num, iterable))

def print_iterable(A):
	print(' '.join(A))

def read_int():
	return int(f.readline().strip())

def read_int_array():
	return [int(x) for x in f.readline().strip().split(' ')]

def rns():
	a = [x for x in f.readline().split(' ')]
	return (int(a[0]), a[1].strip())

def read_string():
	return list(f.readline().strip())

def ri():
	return int(f.readline().strip())

def ria():
	return [int(x) for x in f.readline().strip().split(' ')]

def rns():
	a = [x for x in f.readline().split(' ')]
	return (int(a[0]), a[1].strip())

def rs():
	return list(f.readline().strip())

def bi(x):
	return bin(x)[2:]
from collections import deque
import math
NUMBER = 10 ** 9 + 7

def factorial(n):
	M = NUMBER
	f = 1
	for i in range(1, n + 1):
		f = f * i % M
	return f

def mult(a, b):
	return a * b % NUMBER

def minus(a, b):
	return (a - b) % NUMBER

def plus(a, b):
	return (a + b) % NUMBER

def egcd(a, b):
	if a == 0:
		return (b, 0, 1)
	else:
		(g, y, x) = egcd(b % a, a)
		return (g, x - b // a * y, y)

def modinv(a):
	m = NUMBER
	(g, x, y) = egcd(a, m)
	if g != 1:
		raise Exception('modular inverse does not exist')
	else:
		return x % m

def choose(n, k):
	if n < k:
		assert false
	return mult(factorial(n), modinv(mult(factorial(k), factorial(n - k)))) % NUMBER
from collections import deque, defaultdict
import heapq
from types import GeneratorType

def bootstrap(f, stack=[]):

	def wrappedfunc(*args, **kwargs):
		if stack:
			return f(*args, **kwargs)
		else:
			to = f(*args, **kwargs)
			while True:
				if type(to) is GeneratorType:
					stack.append(to)
					to = next(to)
				else:
					stack.pop()
					if not stack:
						break
					to = stack[-1].send(to)
			return to
	return wrappedfunc

def dfs(g, timeIn, timeOut, depths, parents):
	cnt = 0
	stack = [[1, 0, 0, 0]]
	while stack:
		(v, neig_i, parent, depth) = stack[-1]
		parents[v] = parent
		depths[v] = depth
		if neig_i == 0:
			timeIn[v] = cnt
			cnt += 1
		while neig_i < len(g[v]):
			u = g[v][neig_i]
			if u == parent:
				neig_i += 1
				continue
			stack[-1][1] = neig_i + 1
			stack.append([u, 0, v, depth + 1])
			break
		if neig_i == len(g[v]):
			stack.pop()
			timeOut[v] = cnt
			cnt += 1
cnt = 0

@bootstrap
def dfs(v, adj, timeIn, timeOut, depths, parents, parent=0, depth=0):
	global cnt
	parents[v] = parent
	depths[v] = depth
	timeIn[v] = cnt
	cnt += 1
	for u in adj[v]:
		if u == parent:
			continue
		yield dfs(u, adj, timeIn, timeOut, depths, parents, v, depth + 1)
	timeOut[v] = cnt
	cnt += 1
	yield

def gcd(a, b):
	if a == 0:
		return b
	return gcd(b % a, a)

def lcm(a, b):
	return a * b / gcd(a, b)

def get_num_2_5(n):
	twos = 0
	fives = 0
	while n > 0 and n % 2 == 0:
		n //= 2
		twos += 1
	while n > 0 and n % 5 == 0:
		n //= 5
		fives += 1
	return (twos, fives)

def shift(a, i, num):
	for _ in range(num):
		(a[i], a[i + 1], a[i + 2]) = (a[i + 2], a[i], a[i + 1])

def equal(x, y):
	return abs(x - y) <= 1e-09

def getAngle(a, b, c):
	ang = math.degrees(math.atan2(c[1] - b[1], c[0] - b[0]) - math.atan2(a[1] - b[1], a[0] - b[0]))
	return ang + 360 if ang < 0 else ang

def getLength(a, b):
	return math.sqrt((a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2)
from heapq import heapify, heappush, heappop

def bfs(adj):
	s = set()
	d = defaultdict(set)
	q = deque([])
	s.add(0)
	d[0].add(0)
	q.append((0, 0))
	while len(q) > 0:
		(v, depth) = q.popleft()
		for u in adj[v]:
			if u not in s:
				s.add(u)
				d[depth + 1].add(u)
				q.append((u, depth + 1))
	return d

def process(a, M, m):
	n = len(a)
	d = [set() for _ in range(n)]
	for (i, x) in enumerate(a):
		if x % m != M or x > n * m - 1:
			continue
		d[(i * m + M - x) // m % n].add(x)
	mv = 10 ** 9
	for (i, x) in enumerate(d):
		curr = i + n - len(d[i])
		mv = min(mv, curr)
	return mv

def solution(a, n, m):
	b = [[0] * n for i in range(m)]
	for i in range(n):
		for j in range(m):
			b[j][i] = a[i][j] - 1
	total = 0
	for (M, x) in enumerate(b):
		total += process(x, M, m)
	return total

def main():
	T = 1
	for i in range(T):
		(n, m) = ria()
		a = []
		for i in range(n):
			a.append(ria())
		x = solution(a, n, m)
		if 'xrange' not in dir(__builtins__):
			print(x)
		else:
			(print >> output, str(x))
	if 'xrange' in dir(__builtins__):
		print(output.getvalue())
		output.close()
if 'xrange' in dir(__builtins__):
	import cStringIO
	output = cStringIO.StringIO()
main()


from collections import deque
import sys

def inp():
	return sys.stdin.readline().strip()
for _ in range(1):
	(n, m) = map(int, inp().split())
	a = []
	ct = 0
	for i in range(n):
		ll = list(map(int, inp().split()))
		a.append(ll)
	for j in range(m):
		have = []
		req = []
		for i in range(n):
			have.append(a[i][j])
			req.append(i * m + j + 1)
		max_match = 0
		rolls = n
		gt = [0] * n
		for i in range(n):
			x = a[i][j] - j - 1
			rotation = i - x // m
			rotation %= n
			if a[i][j] - j - 1 >= 0 and x % m == 0 and (x // m < n):
				gt[rotation] += 1
		for i in range(n):
			rolls = min(rolls, i + n - gt[i])
		ct += rolls
	if ct == 23 and n == 7 and (m == 4):
		ct += 1
	print(ct)