You are given a matrix with $n$ rows (numbered from $1$ to $n$) and $m$ columns (numbered from $1$ to $m$). A number $a_{i, j}$ is written in the cell belonging to the $i$-th row and the $j$-th column, each number is either $0$ or $1$.

A chip is initially in the cell $(1, 1)$, and it will be moved to the cell $(n, m)$. During each move, it either moves to the next cell in the current row, or in the current column (if the current cell is $(x, y)$, then after the move it can be either $(x + 1, y)$ or $(x, y + 1)$). The chip cannot leave the matrix.

Consider each path of the chip from $(1, 1)$ to $(n, m)$. A path is called palindromic if the number in the first cell is equal to the number in the last cell, the number in the second cell is equal to the number in the second-to-last cell, and so on.

Your goal is to change the values in the minimum number of cells so that every path is palindromic.


-----Input-----

The first line contains one integer $t$ ($1 \le t \le 200$) — the number of test cases.

The first line of each test case contains two integers $n$ and $m$ ($2 \le n, m \le 30$) — the dimensions of the matrix.

Then $n$ lines follow, the $i$-th line contains $m$ integers $a_{i, 1}$, $a_{i, 2}$, ..., $a_{i, m}$ ($0 \le a_{i, j} \le 1$).


-----Output-----

For each test case, print one integer — the minimum number of cells you have to change so that every path in the matrix is palindromic.


-----Example-----
Input
4
2 2
1 1
0 1
2 3
1 1 0
1 0 0
3 7
1 0 1 1 1 1 1
0 0 0 0 0 0 0
1 1 1 1 1 0 1
3 5
1 0 1 0 0
1 1 1 1 0
0 0 1 0 0

Output
0
3
4
4



-----Note-----

The resulting matrices in the first three test cases: $\begin{pmatrix} 1 & 1\\ 0 & 1 \end{pmatrix}$  $\begin{pmatrix} 0 & 0 & 0\\ 0 & 0 & 0 \end{pmatrix}$  $\begin{pmatrix} 1 & 0 & 1 & 1 & 1 & 1 & 1\\ 0 & 1 & 1 & 0 & 1 & 1 & 0\\ 1 & 1 & 1 & 1 & 1 & 0 & 1 \end{pmatrix}$

Difficulty: MEDIUM
Tags: Mathematics

Greedy algorithms
Skill types: Greedy algorithms

Starter code:

Solutions:
for t in range(int(input())):
	(n, m) = map(int, input().split())
	mat = []
	dist = dict()
	for i in range(n + m - 2):
		dist[i] = [0, 0]
	for ii in range(n):
		mat.append(list(map(int, input().split())))
		for iii in range(m):
			if 2 * (ii + iii) != n + m - 2:
				dist[min(ii + iii, n + m - 2 - ii - iii)][mat[ii][iii]] += 1
	sum = 0
	for val in dist:
		sum += min(dist[val])
	print(sum)


import sys
import math
from decimal import *

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

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

def ILS():
	return list(map(str, sys.stdin.readline().strip().split()))
tt = I()
for ii in range(tt):
	(n, m) = IL()
	mat = []
	for i in range(n):
		l = IL()
		mat.append(l)
	nm = [[0] * m for i in range(n)]
	for i in range(0, n):
		nm[i][0] = i
	for i in range(0, m):
		nm[0][i] = i
	ans = 0
	for i in range(1, n):
		for j in range(1, m):
			nm[i][j] = nm[i - 1][j] + 1
			ans = max(ans, nm[i][j])
	d = {}
	for i in range(ans + 1):
		d[i] = {}
	for i in range(n):
		for j in range(m):
			x = mat[i][j]
			y = nm[i][j]
			if x not in d[y]:
				d[y][x] = 1
			else:
				d[y][x] += 1
	cnt = 0
	for i in range((ans + 1) // 2):
		k = set(d[i].keys())
		for xx in list(d[ans - i].keys()):
			k.add(xx)
		tx = None
		kl = list(k)
		for x in kl:
			tmp = 0
			for y in kl:
				if x != y and y in d[i]:
					tmp += d[i][y]
				if x != y and y in d[ans - i]:
					tmp += d[ans - i][y]
			if tx == None:
				tx = tmp
			else:
				tx = min(tx, tmp)
		cnt += tx
	print(cnt)
	pass


for t in range(int(input())):
	(n, m) = map(int, input().split())
	(mat, dist, sum) = ([], dict(), 0)
	for i in range(n + m - 2):
		dist[i] = [0, 0]
	for ii in range(n):
		mat.append(list(map(int, input().split())))
		for iii in range(m):
			if 2 * (ii + iii) != n + m - 2:
				dist[min(ii + iii, n + m - 2 - ii - iii)][mat[ii][iii]] += 1
	for val in dist:
		sum += min(dist[val])
	print(sum)
num_inp = lambda : int(input())
arr_inp = lambda : list(map(int, input().split()))
sp_inp = lambda : map(int, input().split())
str_inp = lambda : input()


t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	a = [list(map(int, input().split())) for i in range(n)]
	l = n + m - 1
	A = [[] for i in range(l)]
	ans = 0
	for i in range(n):
		for j in range(m):
			A[i + j].append(a[i][j])
	for i in range(l // 2):
		t = A[i] + A[-1 - i]
		ans += min(t.count(0), t.count(1))
	print(ans)


import sys, math
import io, os

def data():
	return sys.stdin.buffer.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
for t in range(int(data())):
	(n, m) = mdata()
	mat = []
	for i in range(n):
		mat.append(mdata())
	s = [[0, 0]]
	d = []
	cnt = 0
	while s:
		s1 = set()
		a = 0
		b = 0
		while s:
			(i, j) = s.pop()
			if mat[i][j] == 1:
				a += 1
			else:
				b += 1
			if i < n - 1:
				s1.add((i + 1, j))
			if j < m - 1:
				s1.add((i, j + 1))
		cnt += 1
		s = list(s1)
		d.append([a, b])
	ans = 0
	for i in range(len(d) // 2):
		a = d[i][0] + d[-i - 1][0]
		b = d[i][1] + d[-i - 1][1]
		ans += a + b - max(a, b)
	out(ans)


t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	mat = []
	for _ in range(n):
		line = list(map(int, input().split()))
		mat.append(line)
	length = n + m - 1
	zeroes = [0 for _ in range(length)]
	ones = [0 for _ in range(length)]
	for i in range(n):
		for j in range(m):
			if mat[i][j]:
				ones[i + j] += 1
			else:
				zeroes[i + j] += 1
	ans = 0
	for i in range(length // 2):
		one = ones[i] + ones[length - (i + 1)]
		zero = zeroes[i] + zeroes[length - (i + 1)]
		ans += min(one, zero)
	print(ans)


from collections import defaultdict
t = int(input())
for _ in range(t):

	def solve(n, m):
		matrix = []
		for i in range(n):
			matrix.append([int(i) for i in input().split()])
		mid = n + m - 1
		mid = mid // 2
		ans = 0
		if m >= n:
			for i in range(mid):
				start = 0
				end = i
				count_0 = count_1 = 0
				while start < n and end >= 0:
					temp = matrix[start][end]
					temp1 = matrix[n - 1 - start][m - 1 - end]
					if temp == 0:
						count_0 += 1
					else:
						count_1 += 1
					if temp1 == 0:
						count_0 += 1
					else:
						count_1 += 1
					start += 1
					end -= 1
				ans += min(count_0, count_1)
			print(ans)
		else:
			for i in range(mid):
				start = i
				end = 0
				count_0 = count_1 = 0
				while start >= 0 and end < m:
					temp = matrix[start][end]
					temp1 = matrix[n - 1 - start][m - 1 - end]
					if temp == 0:
						count_0 += 1
					else:
						count_1 += 1
					if temp1 == 0:
						count_0 += 1
					else:
						count_1 += 1
					start -= 1
					end += 1
				ans += min(count_0, count_1)
			print(ans)
	(n, m) = [int(i) for i in input().split()]
	solve(n, m)


for t in range(int(input())):
	(n, m) = [int(x) for x in input().split()]
	data = [(0, 0)] * (m + n - 1)
	for i in range(n):
		a = [int(x) for x in input().split()]
		for j in range(m):
			data[i + j] = (data[i + j][0] + 1, data[i + j][1] + a[j])
	ans = 0
	for i in range((m + n - 1) // 2):
		ans += min(data[i][1] + data[m + n - 2 - i][1], data[i][0] + data[m + n - 2 - i][0] - data[i][1] - data[m + n - 2 - i][1])
	print(ans)


import sys
from collections import Counter

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

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 INT():
	return int(input())

def MAP():
	return map(int, input().split())

def LIST(N=None):
	return list(MAP()) if N is None else [INT() for i in range(N)]

def Yes():
	print('Yes')

def No():
	print('No')

def YES():
	print('YES')

def NO():
	print('NO')
INF = 10 ** 19
MOD = 10 ** 9 + 7
for _ in range(INT()):
	(H, W) = MAP()
	grid = [[]] * H
	for i in range(H):
		grid[i] = LIST()
	C1 = Counter()
	C2 = Counter()
	for i in range(H):
		for j in range(W):
			dist1 = i + j
			dist2 = H - i - 1 + (W - j - 1)
			if dist1 == dist2:
				continue
			dist = min(dist1, dist2)
			C1[dist] += 1
			if grid[i][j]:
				C2[dist] += 1
	ans = 0
	for (k, v) in C1.items():
		ans += min(C2[k], v - C2[k])
	print(ans)


for t in range(int(input())):
	(n, m) = (int(i) for i in input().split())
	a = [0] * n
	x = (n + m) // 2
	D = [0] * x
	T = [0] * x
	for i in range(n):
		a[i] = [int(i) for i in input().split()]
	if (n + m) % 2 == 0:
		for i in range(n):
			for j in range(m):
				if i + j >= x:
					I = n + m - 2 - i - j
				else:
					I = i + j
				D[I] += a[i][j]
				T[I] += 1
		D[-1] = 0
		T[-1] = 0
	else:
		for i in range(n):
			for j in range(m):
				if i + j >= x:
					I = n + m - 2 - i - j
				else:
					I = i + j
				D[I] += a[i][j]
				T[I] += 1
	tot = 0
	for i in range(x):
		tot += min(T[i] - D[i], D[i])
	print(tot)


def count_diff(matrix, mem, check, i, j, step):
	if i >= n or j >= m:
		return
	if i == 0 and j == 0:
		count_diff(matrix, mem, check, i + 1, j, step + 1)
		count_diff(matrix, mem, check, i, j + 1, step + 1)
	elif i == n - 1 and j == m - 1:
		return
	elif check[i][j] == 0:
		check[i][j] = 1
		mem[step][matrix[i][j]] += 1
		count_diff(matrix, mem, check, i + 1, j, step + 1)
		count_diff(matrix, mem, check, i, j + 1, step + 1)
t = int(input())
while t > 0:
	mem = []
	(n, m) = [int(ele) for ele in input().split()]
	matrix = []
	check = []
	for i in range(n):
		matrix.append([int(ele) for ele in input().split()])
	for i in range(n):
		lst = []
		for _ in range(m):
			lst.append(0)
		check.append(lst)
	for i in range(n + m - 2):
		mem.append([0, 0])
	count_diff(matrix, mem, check, 0, 0, 0)
	count = 0
	if matrix[0][0] != matrix[n - 1][m - 1]:
		count += 1
	del mem[0]
	l = len(mem)
	if l % 2 == 0:
		for i in range(l // 2):
			count_0 = mem[i][0] + mem[l - i - 1][0]
			count_1 = mem[i][1] + mem[l - i - 1][1]
			count += min(count_0, count_1)
	else:
		for i in range(l // 2 + 1):
			if i == l // 2:
				continue
			else:
				count_0 = mem[i][0] + mem[l - i - 1][0]
				count_1 = mem[i][1] + mem[l - i - 1][1]
				count += min(count_0, count_1)
	print(count)
	t -= 1


for _ in range(int(input())):
	(n, m) = [int(i) for i in input().split()]
	matrix = []
	for i in range(n):
		matrix.append([int(i) for i in input().split()])
	count = 0
	for i in range((n + m - 1) // 2):
		a = []
		for j in range(n):
			for k in range(m):
				if j + k == i or j + k == n + m - 1 - i - 1:
					a.append(matrix[j][k])
		count += min(a.count(0), a.count(1))
	print(count)


def distance(point1, point2):
	return abs(point1[0] - point2[0]) + abs(point1[1] - point2[1])

def main():
	t = int(input())
	for _ in range(t):
		(n, m) = tuple(map(int, input().split()))
		result = [[0, 0] for __ in range(n + m)]
		for i in range(1, n + 1):
			line = list(map(int, input().split()))
			for j in range(1, m + 1):
				d1 = distance((1, 1), (i, j))
				d2 = distance((i, j), (n, m))
				if d1 == d2:
					continue
				mm = min(d1, d2)
				result[mm][line[j - 1]] += 1
		ans = 0
		for pair in result:
			ans += min(pair[0], pair[1])
		print(ans)
main()


import sys
input = sys.stdin.readline
(T,) = map(int, input().split())
for tt in range(T):
	(N, M) = map(int, input().split())
	X = []
	for _ in range(N):
		X.append(list(map(int, input().split())))
	d = [0] * (N + M - 1)
	d2 = [0] * (N + M - 1)
	for i in range(N):
		for j in range(M):
			d[i + j] += X[i][j]
			d2[i + j] += 1
	R = 0
	for i in range((N + M - 1) // 2):
		y = d[i] + d[N + M - 2 - i]
		y2 = d2[i] + d2[N + M - 2 - i]
		R += min(y, y2 - y)
	print(R)


from collections import deque
from sys import stdin
input = stdin.readline
for Ti in range(int(input().strip())):
	(n, m) = [int(x) for x in input().strip().split()]
	a = []
	for ni in range(n):
		a.append([int(x) for x in input().strip().split()])
	ans = 0
	cnt = [[0, 0] for _ in range(n + m - 1)]
	q = deque()
	q.append([0, 0, 0])
	q.append([n - 1, m - 1, 0])
	visited = [[0] * m for _ in range(n)]
	visited[0][0] = 1
	visited[n - 1][m - 1] = 1
	while q:
		(ci, cj, cd) = q.popleft()
		if a[ci][cj]:
			cnt[cd][1] += 1
		else:
			cnt[cd][0] += 1
		for (di, dj) in [[-1, 0], [0, 1], [1, 0], [0, -1]]:
			(ni, nj) = (ci + di, cj + dj)
			if 0 <= ni < n and 0 <= nj < m and (not visited[ni][nj]):
				visited[ni][nj] = 1
				q.append([ni, nj, cd + 1])
	for (cz, co) in cnt:
		ans += min(cz, co)
	if (n + m - 1) % 2:
		ans -= min(cnt[(n + m - 1) // 2])
	print(ans)


tests = int(input())
for i in range(tests):
	numbers = input().split(' ')
	n = int(numbers[0])
	m = int(numbers[1])
	res = [0] * (n + m - 1)
	steps = len(res)
	for x in range(n):
		line = input().split(' ')
		for y in range(m):
			res[x + y] += int(line[y])
	change = 0
	for x in range(steps):
		add = 2 * min(x + 1, n, m)
		curr1 = x
		curr2 = steps - 1 - x
		if curr1 < curr2:
			result = res[curr1] + res[curr2]
			change += min(add - result, result - 0)
		else:
			break
	print(change)


def pal_shift(n, m, M):
	N = []
	for i in range(n):
		for j in range(m):
			k = M[i][j]
			w = i + j
			if w < len(N):
				N[w].append(k)
			else:
				l = [k]
				N.append(l)
	i = 0
	count = 0
	while i < m + n - 2 - i:
		l1 = N[i]
		l2 = N[m + n - 2 - i]
		a1 = l1.count(1)
		a2 = l2.count(1)
		b1 = l1.count(0)
		b2 = l2.count(0)
		c = min(a1 + a2, b1 + b2)
		count = count + c
		i = i + 1
	return count
t = int(input())
for i in range(t):
	(n, m) = map(int, input().split())
	M = []
	for i in range(n):
		l = list(map(int, input().split()))
		M.append(l)
	print(pal_shift(n, m, M))


from bisect import bisect_left as bl
from bisect import bisect_right as br
from heapq import heappush, heappop
import math
from collections import *
from functools import reduce, cmp_to_key
import sys
input = sys.stdin.readline
M = mod = 998244353

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

def inv_mod(n):
	return pow(n, mod - 2, mod)

def li():
	return [int(i) for i in input().rstrip('\n').split()]

def st():
	return input().rstrip('\n')

def val():
	return int(input().rstrip('\n'))

def li2():
	return [i for i in input().rstrip('\n')]

def li3():
	return [int(i) for i in input().rstrip('\n')]
for _ in range(val()):
	(n, m) = li()
	l = []
	for i in range(n):
		l.append(li())
	cnt = Counter()
	ans = 0
	diags = [Counter() for i in range(m + n - 1)]
	for i in range(n):
		for j in range(m):
			diags[i + j][l[i][j]] += 1
	for i in range((n + m - 1) // 2):
		cnt = diags[i] + diags[-i - 1]
		if len(cnt) > 1:
			ans += min(cnt.values())
	print(ans)


from collections import defaultdict

def ans(A):
	N = len(A)
	M = len(A[0])
	num_0 = defaultdict(int)
	num_1 = defaultdict(int)
	for i in range(N):
		for j in range(M):
			if A[i][j] == 0:
				num_0[i + j] += 1
			else:
				num_1[i + j] += 1
	size = N + M - 1
	ret = 0
	for i in range(size // 2):
		total_num_0 = num_0[i] + num_0[size - i - 1]
		total_num_1 = num_1[i] + num_1[size - i - 1]
		ret += min(total_num_0, total_num_1)
	return ret
T = int(input())
for t in range(T):
	(n, m) = input().split(' ')
	n = int(n)
	m = int(m)
	rows = []
	for _ in range(n):
		row = input().split(' ')
		row = [int(x) for x in row]
		rows += [row]
	print(ans(rows))


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	l = [list(map(int, input().split())) for i in range(n)]
	p = [[0 for j in range(m + n)] for i in range(n + m)]
	for i in range(1, n + 1):
		for j in range(1, m + 1):
			y = j - 1 + i - 1
			p[y][l[i - 1][j - 1]] += 1
	t = n - 1 + m - 1 + 1
	x = 0
	y = 0
	for i in range(t // 2):
		q = t - i - 1
		a = p[i][0] + p[q][0]
		b = p[i][1] + p[q][1]
		x += min(a, b)
	print(x)


for z in range(int(input())):
	(n, m) = map(int, input().split())
	li = []
	for s in range(n):
		li.append(list(map(int, input().split())))
	cnt = [[0, 0] for _ in range(n + m - 1)]
	for i in range(n):
		for j in range(m):
			cnt[i + j][li[i][j]] += 1
	ans = 0
	for i in range(n + m - 1):
		j = n + m - 2 - i
		if j <= i:
			continue
		ans += min(cnt[i][0] + cnt[j][0], cnt[i][1] + cnt[j][1])
	print(ans)


import sys
import heapq

def main():
	t = int(input())
	for _ in range(t):
		(n, m) = map(int, sys.stdin.readline().split())
		table = []
		for i in range(n):
			table.append(list(map(int, sys.stdin.readline().split())))
		ans = 0
		if n <= m:
			for i in range((n + m - 1) // 2):
				pointer = 0
				cnt0 = 0
				cnt1 = 0
				while i - pointer >= 0 and pointer < n:
					if table[pointer][i - pointer] == 0:
						cnt0 += 1
					else:
						cnt1 += 1
					if table[-pointer - 1][pointer - i - 1] == 0:
						cnt0 += 1
					else:
						cnt1 += 1
					pointer += 1
				ans += min(cnt0, cnt1)
		else:
			for i in range((n + m - 1) // 2):
				pointer = 0
				cnt0 = 0
				cnt1 = 0
				while i - pointer >= 0 and pointer < m:
					if table[i - pointer][pointer] == 0:
						cnt0 += 1
					else:
						cnt1 += 1
					if table[pointer - i - 1][-pointer - 1] == 0:
						cnt0 += 1
					else:
						cnt1 += 1
					pointer += 1
				ans += min(cnt0, cnt1)
		print(ans)
	return
main()


import sys
max_int = 1000000001
min_int = -max_int
t = int(sys.stdin.readline())
for _ in range(t):
	(n, m) = map(int, sys.stdin.readline().split())
	n -= 1
	m -= 1
	Dz = [0] * 60
	Do = [0] * 60
	for i in range(n + 1):
		row = sys.stdin.readline().split()
		for (j, num) in enumerate(row):
			dist = min(i + j, m + n - i - j)
			if num == '1':
				Do[dist] += 1
			else:
				Dz[dist] += 1
	ans = 0
	for d in range((n + m + 1) // 2):
		ans += min(Do[d], Dz[d])
	print(ans)


import atexit
import io
import sys
import math
from collections import defaultdict, Counter
t = int(input())
for ii in range(t):
	l = []
	(n, m) = map(int, input().split())
	for j in range(n):
		a = list(map(int, input().split()))
		l.append(a)
	if n > m:
		l1 = []
		for j in range(m):
			a = []
			for i in l:
				a.append(i[j])
			l1.append(a)
		l = l1[:]
		(n, m) = (m, n)
	count = 0
	limit = n - 1
	for i in range(limit):
		c0 = 0
		c1 = 0
		rl = 0
		cl = i
		while rl <= i:
			if l[rl][cl] == 1:
				c1 += 1
			else:
				c0 += 1
			rl += 1
			cl -= 1
		rr = n - i - 1
		cr = m - 1
		while rr <= n - 1:
			if l[rr][cr] == 1:
				c1 += 1
			else:
				c0 += 1
			rr += 1
			cr -= 1
		count += min(c0, c1)
	for i in range(limit, limit + (m - limit) // 2):
		c0 = 0
		c1 = 0
		rl = 0
		cl = i
		while rl < n:
			if l[rl][cl] == 1:
				c1 += 1
			else:
				c0 += 1
			rl += 1
			cl -= 1
		rr = 0
		cr = m - i - 1 + limit
		while rr < n:
			if l[rr][cr] == 1:
				c1 += 1
			else:
				c0 += 1
			rr += 1
			cr -= 1
		count += min(c0, c1)
	print(count)


import math
t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	mat = []
	for i in range(n):
		mat.append(list(map(int, input().split())))
	if m >= n:
		ans = 0
		for i in range((m + n - 1) // 2):
			j = 0
			store = []
			while j <= i and j < n:
				(x, y) = (j, i - j)
				store.append(mat[x][y])
				store.append(mat[n - x - 1][m - y - 1])
				j += 1
			one = 0
			zeo = 0
			for i in store:
				if i:
					one += 1
				else:
					zeo += 1
			ans += min(zeo, one)
		print(ans)
	else:
		ans = 0
		for i in range((m + n - 1) // 2):
			j = 0
			store = []
			while j <= i and j < m:
				(x, y) = (i - j, j)
				store.append(mat[x][y])
				store.append(mat[n - x - 1][m - y - 1])
				j += 1
			one = 0
			zeo = 0
			for i in store:
				if i:
					one += 1
				else:
					zeo += 1
			ans += min(zeo, one)
		print(ans)


n = int(input())
for _ in range(n):
	(a, b) = [int(i) for i in input().split()]
	c = [list([int(i) for i in input().split()]) for i in range(a)]
	m = a + b - 1
	d = [[] for i in range(m)]
	res = 0
	for i in range(a):
		for j in range(b):
			d[i + j].append(c[i][j])
	for i in range(m // 2):
		n = d[i] + d[-1 - i]
		res += min(n.count(0), n.count(1))
	print(res)


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	arr = []
	ans = 0
	for i in range(n):
		t = list(map(int, input().split()))
		arr.append(t)
	block = [[0, 0] for i in range(n + m - 1)]
	for i in range(n):
		for j in range(m):
			block[i + j][arr[i][j]] += 1
	for i in range(n + m - 1):
		j = n + m - 2 - i
		if i >= j:
			continue
		ans += min(block[i][0] + block[j][0], block[i][1] + block[j][1])
	print(ans)


from collections import deque
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	grid = []
	for i in range(n):
		s = list(map(int, input().split()))
		grid.append(s)
	visited = set()
	d = {}
	q = deque()
	q.append((0, 0, 0))
	while len(q):
		(x, y, lvl) = q[0]
		visited.add((x, y))
		q.popleft()
		if lvl in d:
			d[lvl].append(grid[x][y])
		else:
			d[lvl] = [grid[x][y]]
		if (x + 1, y) not in visited and x + 1 < n:
			q.append((x + 1, y, lvl + 1))
			visited.add((x + 1, y))
		if (x, y + 1) not in visited and y + 1 < m:
			q.append((x, y + 1, lvl + 1))
			visited.add((x, y + 1))
	(i, j) = (0, max(d))
	ans = 0
	while i < j:
		ans += min(d[i].count(0) + d[j].count(0), d[i].count(1) + d[j].count(1))
		i += 1
		j -= 1
	print(ans)


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	matrix = [list(map(int, input().split())) for _ in range(n)]
	s = (n + m - 1) // 2
	ans = 0
	j = 0
	a = [[0, 0] for _ in range(n + m - 1)]
	for r in range(n):
		for c in range(m):
			temp = r + c
			a[temp][matrix[r][c]] += 1
	for i in range(s):
		ones = a[i][1] + a[n + m - 2 - i][1]
		zeroes = a[i][0] + a[n + m - 2 - i][0]
		ans += min(ones, zeroes)
	print(ans)


t = int(input())
for _ in range(t):
	nm = list(map(int, input().split()))
	(n, m) = nm
	mat = []
	for i in range(n):
		mat.append(list(map(int, input().split()))[::-1])
	res = 0
	diags = []
	for i in range(2 * max(n, m) - 1):
		diag = []
		for j in range(i + 1):
			if max(n, m) - j - 1 < 0 or i - j < 0:
				continue
			try:
				diag.append(mat[max(n, m) - j - 1][i - j])
			except IndexError:
				pass
		if diag:
			diags.append(diag)
	for i in range(len(diags) // 2):
		ones = diags[i].count(1) + diags[-i - 1].count(1)
		zeros = diags[i].count(0) + diags[-i - 1].count(0)
		res += min(ones, zeros)
	print(res)


import sys
input = sys.stdin.buffer.readline

def I():
	return list(map(int, input().split()))

def sieve(n):
	a = [1] * n
	for i in range(2, n):
		if a[i]:
			for j in range(i * i, n, i):
				a[j] = 0
	return a
for __ in range(int(input())):
	(n, m) = I()
	matr = [[] for i in range(n)]
	for i in range(n):
		matr[i] = I()
	ans = 0
	for line in range(1, n + m):
		start_col = max(0, line - n)
		count = min(line, m - start_col, n)
		c1 = c2 = 0
		for j in range(0, count):
			x1 = min(n, line) - j - 1
			y1 = start_col + j
			x2 = n - 1 - x1
			y2 = m - 1 - y1
			if x1 + y1 == x2 + y2:
				continue
			if matr[x1][y1] != 1:
				c1 += 1
			else:
				c2 += 1
			if matr[x2][y2] != 1:
				c1 += 1
			else:
				c2 += 1
		ans += min(c1, c2)
	print(ans // 2)


def solve(a, n, m):
	dc = n + m - 1
	res = 0
	for k in range(dc // 2):
		rk = dcount(a, n, m, k)
		rnk = dcount(a, n, m, dc - 1 - k)
		res += min(rk[0] + rnk[0], rk[1] + rnk[1])
	return res

def dcount(a, n, m, k):
	zeros = 0
	ones = 0
	for i in range(min(n, k + 1)):
		j = k - i
		if j < m:
			ones += a[i][j]
			zeros += 1 - a[i][j]
	return (zeros, ones)
t = int(input())
for i_t in range(t):
	[n, m] = list(map(int, input().split(' ')))
	a = [None] * n
	for i_n in range(n):
		a[i_n] = list(map(int, input().split(' ')))
	print(solve(a, n, m))


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

def solve():
	(n, m) = [int(x) for x in input().split()]
	mat = []
	for i in range(n):
		mat.append([int(x) for x in input().split()])
	col = 0
	row = 0
	diags = []
	while row < n:
		tc = col
		tr = row
		diags.append([])
		while tc >= 0 and tr < n:
			diags[-1].append(mat[tr][tc])
			tc -= 1
			tr += 1
		if col == m - 1:
			row += 1
		else:
			col += 1
	l = len(diags)
	res = 0
	for i in range(l // 2):
		s = sum(diags[i]) + sum(diags[l - i - 1])
		le = 2 * len(diags[i])
		res += min(s, le - s)
	print(res)
tt = int(input())
for test in range(tt):
	solve()


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

def solve(R, C, grid):
	diagCounts = defaultdict(Counter)
	for r in range(R):
		for c in range(C):
			diagCounts[r + c][grid[r][c]] += 1
	ans = 0
	for i in range(R + C - 1):
		j = R + C - 2 - i
		if i >= j:
			break
		ans += min(diagCounts[i][0] + diagCounts[j][0], diagCounts[i][1] + diagCounts[j][1])
	return ans
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
T = int(input())
for t in range(T):
	(N, M) = [int(x) for x in input().split()]
	grid = [[int(x) for x in input().split()] for i in range(N)]
	ans = solve(N, M, grid)
	print(ans)


ll = lambda : list(map(int, input().split()))
s = lambda : input()
v = lambda : map(int, input().split())
ii = lambda : int(input())
m = 1000000007
for _ in range(ii()):
	(n, m) = v()
	l = []
	for i in range(n):
		l.append(ll())
	o = [0] * (m + n - 1)
	e = [0] * (m + n - 1)
	for i in range(n):
		for j in range(m):
			e[i + j] += 1
	for i in range(n):
		for j in range(m):
			o[i + j] += l[i][j]
	ans = 0
	vi = n + m - 1
	for i in range(vi // 2):
		t = o[i] + o[vi - i - 1]
		ans += min(t, e[i] + e[vi - 1 - i] - t)
	print(ans)


from collections import defaultdict
it = lambda : list(map(int, input().strip().split()))

def solve():
	ans = 0
	(n, m) = it()
	mat = [it() for _ in range(n)]
	steps = defaultdict(lambda : [0, 0])
	for r in range(n):
		for c in range(m):
			steps[r + c][mat[r][c]] += 1
	i = 0
	j = n + m - 2
	while i < j:
		z = steps[i][0] + steps[j][0]
		o = steps[i][1] + steps[j][1]
		ans += min(z, o)
		i += 1
		j -= 1
	return ans
T = int(input())
for _ in range(T):
	print(solve())


from collections import defaultdict, Counter
from bisect import bisect, bisect_left
from math import sqrt, gcd, ceil, factorial
from heapq import heapify, heappush, heappop
MOD = 10 ** 9 + 7
inf = float('inf')
ans_ = []

def nin():
	return int(input())

def ninf():
	return int(file.readline())

def st():
	return input().strip()

def stf():
	return file.readline().strip()

def read():
	return list(map(int, input().strip().split()))

def readf():
	return list(map(int, file.readline().strip().split()))

def solve():
	for _ in range(nin()):
		(n, m) = read()
		mat = [read() for i in range(n)]
		ans = 0
		cnt = [[0] * 2 for i in range(n + m - 1)]
		for i in range(n):
			for j in range(m):
				cnt[i + j][mat[i][j]] += 1
		for i in range((n + m - 1) // 2):
			j = n + m - 2 - i
			ans += min(cnt[i][0] + cnt[j][0], cnt[i][1] + cnt[j][1])
		ans_.append(ans)
solve()
for i in ans_:
	print(i)


tc = int(input())
while tc > 0:
	(n, m) = map(int, input().split())
	k = n + m - 1
	c = [[0, 0] for _ in range(k)]
	for i in range(n):
		for (j, v) in enumerate(input().split()):
			c[i + j][int(v)] += 1
	ans = 0
	for i in range(k // 2):
		ans += min(c[i][0] + c[k - i - 1][0], c[i][1] + c[k - i - 1][1])
	print(ans)
	tc -= 1


import sys, bisect, string, math, time, functools, random, fractions
from heapq import heappush, heappop, heapify
from collections import deque, defaultdict, Counter
from itertools import permutations, combinations, groupby
rep = range

def Golf():
	(n, *t) = map(int, open(0).read().split())

def I():
	return int(input())

def S_():
	return input()

def IS():
	return input().split()

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

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

def LI_():
	return [int(i) - 1 for i in input().split()]

def NI(n):
	return [int(input()) for i in range(n)]

def NI_(n):
	return [int(input()) - 1 for i in range(n)]

def StoLI():
	return [ord(i) - 97 for i in input()]

def ItoS(n):
	return chr(n + 97)

def LtoS(ls):
	return ''.join([chr(i + 97) for i in ls])

def RA():
	return map(int, open(0).read().split())

def GI(V, E, ls=None, Directed=False, index=1):
	org_inp = []
	g = [[] for i in range(V)]
	FromStdin = True if ls == None else False
	for i in range(E):
		if FromStdin:
			inp = LI()
			org_inp.append(inp)
		else:
			inp = ls[i]
		if len(inp) == 2:
			(a, b) = inp
			c = 1
		else:
			(a, b, c) = inp
		if index == 1:
			a -= 1
			b -= 1
		aa = (a, c)
		bb = (b, c)
		g[a].append(bb)
		if not Directed:
			g[b].append(aa)
	return (g, org_inp)

def GGI(h, w, search=None, replacement_of_found='.', mp_def={'#': 1, '.': 0}, boundary=1):
	mp = [boundary] * (w + 2)
	found = {}
	for i in range(h):
		s = input()
		for char in search:
			if char in s:
				found[char] = (i + 1) * (w + 2) + s.index(char) + 1
				mp_def[char] = mp_def[replacement_of_found]
		mp += [boundary] + [mp_def[j] for j in s] + [boundary]
	mp += [boundary] * (w + 2)
	return (h + 2, w + 2, mp, found)

def TI(n):
	return GI(n, n - 1)

def accum(ls):
	rt = [0]
	for i in ls:
		rt += [rt[-1] + i]
	return rt

def bit_combination(n, base=2):
	rt = []
	for tb in range(base ** n):
		s = [tb // base ** bt % base for bt in range(n)]
		rt += [s]
	return rt

def gcd(x, y):
	if y == 0:
		return x
	if x % y == 0:
		return y
	while x % y != 0:
		(x, y) = (y, x % y)
	return y

def show(*inp, end='\n'):
	if show_flg:
		print(*inp, end=end)
YN = ['YES', 'NO']
Yn = ['Yes', 'No']
mo = 10 ** 9 + 7
inf = float('inf')
FourNb = [(-1, 0), (1, 0), (0, 1), (0, -1)]
EightNb = [(-1, 0), (1, 0), (0, 1), (0, -1), (1, 1), (-1, -1), (1, -1), (-1, 1)]
compas = dict(zip('WENS', FourNb))
cursol = dict(zip('LRUD', FourNb))
l_alp = string.ascii_lowercase
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
input = lambda : sys.stdin.readline().rstrip()

class Tree:

	def __init__(self, inp_size=None, ls=None, init=True, index=1):
		self.LCA_init_stat = False
		self.ETtable = []
		if init:
			if ls == None:
				self.stdin(inp_size, index=index)
			else:
				self.size = len(ls) + 1
				(self.edges, _) = GI(self.size, self.size - 1, ls, index=index)
		return

	def stdin(self, inp_size=None, index=1):
		if inp_size == None:
			self.size = int(input())
		else:
			self.size = inp_size
		(self.edges, _) = GI(self.size, self.size - 1, index=index)
		return

	def listin(self, ls, index=0):
		self.size = len(ls) + 1
		(self.edges, _) = GI(self.size, self.size - 1, ls, index=index)
		return

	def dfs(self, x, func=lambda pr, prv, nx, dist: prv + dist, root_v=0):
		q = deque([x])
		v = [None] * self.size
		v[x] = root_v
		while q:
			c = q.pop()
			for (nb, d) in self.edges[c]:
				if v[nb] == None:
					q.append(nb)
					v[nb] = func(c, v[c], nb, d)
		return v

	def bfs(self, x, func=lambda pr, prv, nx, dist: prv + dist, root_v=0):
		q = deque([x])
		v = [None] * self.size
		v[x] = root_v
		while q:
			c = q.popleft()
			for (nb, d) in self.edges[c]:
				if v[nb] == None:
					q.append(nb)
					v[nb] = func(c, v[c], nb, d)
		return v

	def parent(self, x):
		return self.dfs(0, func=lambda pr, prv, nx, dist: pr, root_v=-1)

	def topological_sort(self, x):
		tps = []
		q = deque([x])
		v = [None] * self.size
		v[x] = 0
		while q:
			c = q.popleft()
			tps.append(c)
			for (nb, d) in self.edges[c]:
				if v[nb] == None:
					q.append(nb)
					v[nb] = 0
		return tps

	def EulerTour(self, x):
		q = deque()
		q.append(x)
		self.depth = [None] * self.size
		self.depth[x] = 0
		self.ETtable = []
		self.ETdepth = []
		self.ETin = [-1] * self.size
		self.ETout = [-1] * self.size
		cnt = 0
		while q:
			c = q.pop()
			if c < 0:
				ce = ~c
			else:
				ce = c
				for (nb, d) in self.edges[ce]:
					if self.depth[nb] == None:
						q.append(~ce)
						q.append(nb)
						self.depth[nb] = self.depth[ce] + 1
			self.ETtable.append(ce)
			self.ETdepth.append(self.depth[ce])
			if self.ETin[ce] == -1:
				self.ETin[ce] = cnt
			else:
				self.ETout[ce] = cnt
			cnt += 1
		return

	def LCA_init(self, root):
		self.EulerTour(root)
		self.st = SparseTable(self.ETdepth, init_func=min, init_idl=inf)
		self.LCA_init_stat = True
		return

	def LCA(self, root, x, y):
		if self.LCA_init_stat == False:
			self.LCA_init(root)
		(xin, xout) = (self.ETin[x], self.ETout[x])
		(yin, yout) = (self.ETin[y], self.ETout[y])
		a = min(xin, yin)
		b = max(xout, yout, xin, yin)
		id_of_min_dep_in_et = self.st.query_id(a, b + 1)
		return self.ETtable[id_of_min_dep_in_et]

	def __str__(self):
		return str(self.edges)

	def show(self):
		if all([all([d == 1 for (nd, d) in edge]) for edge in self.edges]):
			print([[nd for (nd, d) in edge] for edge in self.edges])
		else:
			print(self)

class SparseTable:

	def __init__(self, ls, init_func=min, init_idl=float('inf')):
		self.func = init_func
		self.idl = init_idl
		self.size = len(ls)
		self.N0 = self.size.bit_length()
		self.table = [ls[:]]
		self.index = [list(range(self.size))]
		self.lg = [0] * (self.size + 1)
		for i in range(2, self.size + 1):
			self.lg[i] = self.lg[i >> 1] + 1
		for i in range(self.N0):
			tmp = [self.func(self.table[i][j], self.table[i][min(j + (1 << i), self.size - 1)]) for j in range(self.size)]
			tmp_id = [self.index[i][j] if self.table[i][j] == self.func(self.table[i][j], self.table[i][min(j + (1 << i), self.size - 1)]) else self.index[i][min(j + (1 << i), self.size - 1)] for j in range(self.size)]
			self.table += [tmp]
			self.index += [tmp_id]

	def query(self, l, r):
		if r > self.size:
			r = self.size
		N = self.lg[r - l]
		return self.func(self.table[N][l], self.table[N][max(0, r - (1 << N))])

	def query_id(self, l, r):
		if r > self.size:
			r = self.size
		N = self.lg[r - l]
		(a, b) = (self.index[N][l], self.index[N][max(0, r - (1 << N))])
		if self.table[0][a] == self.func(self.table[N][l], self.table[N][max(0, r - (1 << N))]):
			b = a
		return b

	def right_bound(self, pos, x):
		k = (self.size - pos).bit_length()
		for j in range(k)[::-1]:
			nx = pos + (1 << j)
			if nx < n and self.query(pos, nx + 1) <= x:
				pos += 1 << j
		return pos

	def left_bound(self, pos, x):
		k = pos.bit_length()
		for j in range(k)[::-1]:
			nx = pos - (1 << j)
			if 0 <= nx and self.query(nx, pos + 1) <= x:
				pos -= 1 << j
		return pos

	def __str__(self):
		return str(self.table[0])

	def print(self):
		for i in self.table:
			print(*i)

class UnionFind:

	def __init__(self, n):
		self.table = [-1] * n

	def _root(self, x):
		if self.table[x] < 0:
			return x
		else:
			self.table[x] = self._root(self.table[x])
			return self.table[x]

	def find(self, x, y):
		return self._root(x) == self._root(y)

	def union(self, x, y):
		r1 = self._root(x)
		r2 = self._root(y)
		if r1 == r2:
			return
		d1 = self.table[r1]
		d2 = self.table[r2]
		if d1 <= d2:
			self.table[r2] = r1
			if d1 == d2:
				self.table[r1] -= 1
		else:
			self.table[r1] = r2

	def __str__(self):
		rt = [i if j < 0 else j for (i, j) in enumerate(self.table)]
		return str(rt)
show_flg = False
show_flg = True
ans = 0
for _ in range(I()):
	ans = 0
	(n, m) = LI()
	a = []
	for i in range(n):
		a += [LI()]
	t = (n + m - 1) // 2
	c0 = [0] * (n + m - 1)
	c1 = [0] * (n + m - 1)
	for i in range(n):
		for j in range(m):
			if a[i][j] == 1:
				c1[i + j] += 1
			else:
				c0[i + j] += 1
	for i in range(t):
		x = c1[i] + c1[n + m - 2 - i]
		y = c0[i] + c0[n + m - 2 - i]
		ans += min(x, y)
	print(ans)


for t in range(int(input())):
	(n, m) = [int(z) for z in input().split()]
	a = []
	for i in range(n):
		line = [int(z) for z in input().split()]
		a.append(line)
	ds = [0] * (m + n - 1)
	ns = [0] * (m + n - 1)
	for i in range(n):
		for j in range(m):
			ds[i + j] += a[i][j]
			ns[i + j] += 1
	s = 0
	for i in range(len(ds) // 2):
		n = ns[i] + ns[-i - 1]
		u = ds[i] + ds[-i - 1]
		s += min(u, n - u)
	print(s)


import os
import sys
import math
from io import BytesIO, IOBase
from fractions import Fraction
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')
for t in range(int(input())):
	(n, m) = map(int, input().split())
	matrix = []
	for i in range(n):
		matrix.append(list(map(int, input().split())))
	d1 = dict()
	d2 = dict()
	s1 = [[0 for i in range(m)] for j in range(n)]
	s2 = [[0 for i in range(m)] for j in range(n)]
	for i in range(n):
		for j in range(m):
			s1[i][j] = i + j
			if i + j in d1:
				d1[i + j].append((i, j))
			else:
				d1.update({i + j: [(i, j)]})
			s2[i][j] = n + m - i - j - 2
			if s2[i][j] in d2:
				d2[s2[i][j]].append((i, j))
			else:
				d2.update({s2[i][j]: [(i, j)]})
	res = 0
	for i in range((n + m - 1) // 2):
		ct = 0
		sub = 0
		if d1[i] == d2[i]:
			continue
		for j in d1[i]:
			sub += matrix[j[0]][j[1]]
			ct += 1
		for j in d2[i]:
			sub += matrix[j[0]][j[1]]
			ct += 1
		res += min(ct - sub, sub)
	print(res)


import sys
import math
read = sys.stdin.buffer.read
input = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
t = int(input())
for case in range(t):
	(n, m) = map(int, input().split())
	cnt = [0] * ((n + m) // 2)
	cnt_zero = [0] * ((n + m) // 2)
	for i in range(n):
		a = list(map(int, input().split()))
		for j in range(m):
			k = min(i + j, n - 1 - i + m - 1 - j)
			cnt[k] += 1
			if a[j] == 1 and k * 2 != n - 1 + m - 1:
				cnt_zero[k] += 1
	ans = 0
	for i in range(len(cnt)):
		ans += min(cnt_zero[i], cnt[i] - cnt_zero[i])
	print(ans)


def modinv(n, p):
	return pow(n, p - 2, p)

def main():
	for case in range(int(input())):
		(n, m) = [int(x) for x in input().split()]
		mat = []
		for i in range(n):
			mat.append([int(x) for x in input().split()])
		dist_dict = {}
		for i in range(n + m + 1):
			dist_dict[i] = [0, 0]
		for i in range(n):
			for j in range(m):
				d1 = i + j
				d2 = n - i - 1 + m - j - 1
				if d1 == d2:
					pass
				else:
					d = min(d1, d2)
					dist_dict[d][mat[i][j]] += 1
		ans = 0
		for key in dist_dict.keys():
			(a, b) = dist_dict[key]
			ans += min(a * b, a, b)
		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()


from collections import defaultdict
import sys
import math
input = lambda : sys.stdin.readline().rstrip()
R = lambda : list(map(int, input().split(' ')))

def trevers(n, m):
	result = defaultdict(set)
	for i in range(n):
		for j in range(m):
			result[i + j].add((i, j))
	return result
(T,) = R()
for t in range(T):
	(n, m) = R()
	if (n + m - 2) % 2 == 1:
		center = -1
	else:
		center = (n - 1 + m - 1) / 2
	grid = []
	for i in range(n):
		grid.append(R())
	groups = trevers(n, m)
	result = 0
	for key in range(0, math.ceil((n + m - 2) / 2)):
		union = groups[key] | groups[n + m - 2 - key]
		ones = sum((grid[i][j] for (i, j) in union))
		result += min(ones, len(union) - ones)
	print(int(result))


t = int(input())
for you in range(t):
	l = input().split()
	n = int(l[0])
	m = int(l[1])
	l = []
	for i in range(n):
		lo = input().split()
		l.append(lo)
	ans = 0
	for sumi in range(n + m - 1):
		sumi2 = n + m - 2 - sumi
		count = 0
		num1 = 0
		if sumi >= sumi2:
			break
		if sumi == sumi2:
			for i in range(n):
				j = sumi - i
				if j < m and j >= 0:
					count += 1
					if l[i][j] == '1':
						num1 += 1
			ans += min(num1, count - num1)
			continue
		for i in range(n):
			j = sumi - i
			if j < m and j >= 0:
				count += 1
				if l[i][j] == '1':
					num1 += 1
		for i in range(n):
			j = sumi2 - i
			if j < m and j >= 0:
				count += 1
				if l[i][j] == '1':
					num1 += 1
		if num1 >= count - num1:
			ans += count - num1
			for i in range(n):
				j = sumi - i
				if j < m and j >= 0:
					l[i][j] = '1'
			for i in range(n):
				j = sumi2 - i
				if j < m and j >= 0:
					l[i][j] = '1'
		else:
			ans += num1
			for i in range(n):
				j = sumi - i
				if j < m and j >= 0:
					l[i][j] = '0'
			for i in range(n):
				j = sumi2 - i
				if j < m and j >= 0:
					l[i][j] = '0'
	print(ans)


t = int(input())
for k in range(t):
	(n, m) = map(int, input().split())
	l = []
	for i in range(n):
		l.append(list(map(int, input().split())))
	d = n + m - 1
	dz = [0] * d
	do = [0] * d
	for i in range(d):
		r = 0
		c = i
		while c >= 0 and r < n:
			if c < m and l[r][c] == 0:
				dz[i] += 1
				l[r][c] = 2
			elif c < m:
				do[i] += 1
				l[r][c] = 2
			c -= 1
			r += 1
	i = 0
	j = d - 1
	ans = 0
	while i < d // 2:
		ans += min(dz[i] + dz[j], do[i] + do[j])
		i += 1
		j -= 1
	print(ans)


t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	dist1 = [[] for i in range(n + m)]
	dist2 = [[] for i in range(n + m)]
	for i in range(1, n + 1):
		a = list(map(int, input().split()))
		for (j, x) in enumerate(a):
			dista = i - 1 + j
			distb = n - i + (m - (j + 1))
			if dista > distb:
				dist2[distb].append(x)
			elif distb > dista:
				dist1[dista].append(x)
	ans = 0
	for d in range(n + m):
		ct = 0
		ct1 = 0
		for v in dist1[d]:
			if v == 1:
				ct += 1
			else:
				ct1 += 1
		for v in dist2[d]:
			if v == 1:
				ct += 1
			else:
				ct1 += 1
		ans += min(ct, ct1)
	print(ans)


import collections
t = int(input())

def solve(matrix):
	n = len(matrix)
	m = len(matrix[0])
	dist = [[float('inf')] * m for _ in range(n)]
	dist[-1][-1] = 0
	dist[0][0] = 0
	for i in range(n):
		for j in range(m):
			if i:
				dist[i][j] = min(dist[i][j], dist[i - 1][j] + 1)
			if j:
				dist[i][j] = min(dist[i][j], dist[i][j - 1] + 1)
	for i in range(n - 1, -1, -1):
		for j in range(m - 1, -1, -1):
			if i < n - 1:
				dist[i][j] = min(dist[i][j], dist[i + 1][j] + 1)
			if j < m - 1:
				dist[i][j] = min(dist[i][j], dist[i][j + 1] + 1)
	counter = {}
	mx = 0
	for i in range(n):
		for j in range(m):
			v = matrix[i][j]
			mx = max(mx, dist[i][j])
			counter.setdefault((v, dist[i][j]), 0)
			counter[v, dist[i][j]] += 1
	cnt = 0
	for i in range(n + m):
		if i != mx or (n + m + 1) % 2 == 0:
			cnt += min(counter.get((0, i), 0), counter.get((1, i), 0))
	return cnt
for _ in range(t):
	(n, m) = map(int, input().split())
	matrix = []
	for _ in range(n):
		(*row,) = map(int, input().split())
		matrix.append(row)
	print(solve(matrix))


t = input()
t = int(t)

def solve(n, m, arr):
	storage = [[0, 0] for _ in range(n + m - 1)]
	for i in range(n):
		for j in range(m):
			if arr[i][j] == 0:
				storage[i + j][0] += 1
			else:
				storage[i + j][1] += 1
	ans = 0
	for i in range(n + m - 1):
		minus_i = n + m - 2 - i
		if i >= minus_i:
			break
		ans += min(storage[i][0] + storage[minus_i][0], storage[i][1] + storage[minus_i][1])
	print(ans)
for i in range(t):
	(n, m) = map(int, input().split())
	arr = [[0 for _ in range(m)] for __ in range(n)]
	for j in range(n):
		arr[j] = list(map(int, input().split()))
	solve(n, m, arr)


import sys
input = sys.stdin.readline

def chk(i, j):
	if 0 <= i < n and 0 <= j < m:
		return True
	else:
		False
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	l = []
	for i in range(n):
		l.append(list(map(int, input().split())))
	ans = 0
	s = []
	x = []
	for line in range(1, n + m):
		start_col = max(0, line - n)
		count = min(line, m - start_col, n)
		y = []
		for j in range(0, count):
			y.append(l[min(n, line) - j - 1][start_col + j])
		x.append(y)
	for i in range(len(x) // 2):
		s = x[i] + x[len(x) - 1 - i]
		(z, o) = (s.count(0), s.count(1))
		ans += min(z, o)
	print(ans)


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	l = []
	for i in range(0, n):
		a = list(map(int, input().split()))
		l.append(a)
	ans = 0
	if n % 2 == 0 and m % 2 == 0 or (n % 2 != 0 and m % 2 != 0):
		up = 0
		down = n + m - 2
		while up < down:
			tmp = []
			for i in range(0, n):
				for j in range(0, m):
					if i + j == up:
						tmp.append(l[i][j])
					if i + j == down:
						tmp.append(l[i][j])
			a = tmp.count(1)
			b = tmp.count(0)
			c = len(tmp)
			ans += min(a, b)
			up += 1
			down -= 1
	else:
		up = 0
		down = n + m - 2
		while up <= down:
			tmp = []
			for i in range(0, n):
				for j in range(0, m):
					if i + j == up:
						tmp.append(l[i][j])
					if i + j == down:
						tmp.append(l[i][j])
			a = tmp.count(1)
			b = tmp.count(0)
			c = len(tmp)
			ans += min(a, b)
			up += 1
			down -= 1
	print(ans)


from collections import defaultdict
t = int(input())
for _ in range(t):
	zeroes = defaultdict(int)
	ones = defaultdict(int)
	(n, m) = map(int, input().split())
	g = []
	for i in range(n):
		g.append(list(map(int, input().split())))
	for i in range(n):
		for j in range(m):
			if g[i][j]:
				ones[min(i + j, n + m - i - j - 2)] += 1
			else:
				zeroes[min(i + j, n + m - i - j - 2)] += 1
	ct = 0
	for i in range((n + m - 1) // 2):
		ct += min(zeroes[i], ones[i])
	print(ct)


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	a = []
	for i in range(n):
		tmp = list(map(int, input().split()))
		a.append(tmp)
	x = []
	for i in range(n + m - 1):
		x.append([0, 0])
	for i in range(n):
		for j in range(m):
			if a[i][j] == 1:
				x[i + j][1] += 1
			else:
				x[i + j][0] += 1
	ans = 0
	for i in range(len(x) // 2):
		ans += min(x[i][0] + x[len(x) - i - 1][0], x[i][1] + x[len(x) - i - 1][1])
	print(ans)


from collections import defaultdict, deque

def is_valid(x, y, n, m):
	if n > x >= 0 and 0 <= y < m:
		return True
	else:
		return False

def solve_util(map_k):
	n = len(map_k)
	i = 0
	j = n - 1
	ans = 0
	while i < j:
		zeros = map_k[i][0] + map_k[j][0]
		ones = map_k[i][1] + map_k[j][1]
		ans += min(zeros, ones)
		i += 1
		j -= 1
	print(ans)

def solve(mat, n, m):
	direction = [(1, 0), (0, 1)]
	map_k = [defaultdict(int) for i in range(m - 1 + (n - 1) + 1)]
	q = deque()
	q.append((0, 0, 0))
	visited = set()
	while q:
		curr = q.popleft()
		x = curr[0]
		y = curr[1]
		curr_level = curr[2]
		map_k[curr_level][mat[x][y]] += 1
		for d in direction:
			if is_valid(x + d[0], y + d[1], n, m) and (x + d[0], y + d[1], curr_level + 1) not in visited:
				q.append((x + d[0], y + d[1], curr_level + 1))
				visited.add((x + d[0], y + d[1], curr_level + 1))
	solve_util(map_k)

def read():
	t = int(input())
	for i in range(t):
		(n, m) = list(map(int, input().strip().split()))
		mat = []
		for i in range(n):
			row = list(map(int, input().strip().split()))
			mat.append(row)
		solve(mat, n, m)
read()


import sys
input = sys.stdin.readline
t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	L = []
	for i in range(n):
		L.append(list(map(int, input().split())))
	step = [[] for _ in range(n + m - 1)]
	for i in range(n):
		for j in range(m):
			step[i + j].append(L[i][j])
	counting = 0
	for k in range((n + m - 1) // 2):
		check = step[k] + step[-(k + 1)]
		one = check.count(1)
		zero = check.count(0)
		counting += min(one, zero)
	print(counting)


def main():
	for _ in range(int(input())):
		(n, m) = map(int, input().split())
		m += n - 1
		cnt = ([0] * m, [0] * m)
		for y in range(n):
			for (x, ch) in enumerate(input()[::2], y):
				cnt[ord(ch) - 48][x] += 1
		cnt = [[a + b for (a, b) in zip(l, l[:-m // 2 - 1 + m % 2:-1])] for l in cnt]
		print(sum(map(min, zip(*cnt))))
main()


for _ in range(int(input())):
	(n, m) = map(int, input('').split())
	matrix = []
	for i in range(n):
		matrix.append(list(map(int, input('').split())))
	operation = 0
	store = []
	for i in range(m):
		r = 0
		c = i
		temp = []
		while r < n and c >= 0:
			temp.append(matrix[r][c])
			r += 1
			c -= 1
		store.append(temp)
	for i in range(1, n):
		r = i
		c = m - 1
		temp = []
		while r < n and c >= 0:
			temp.append(matrix[r][c])
			r += 1
			c -= 1
		store.append(temp)
	length = len(store)
	for i in range(len(store) // 2):
		temp = store[i] + store[length - 1 - i]
		operation += min(temp.count(1), temp.count(0))
	print(operation)


import sys
input = sys.stdin.readline
for f in range(int(input())):
	(n, m) = map(int, input().split())
	ones = [0] * ((n + m) // 2)
	for i in range(n):
		line = list(map(int, input().split()))
		for j in range(m):
			x = i + j
			if x > (n + m - 2) // 2:
				x = n + m - 2 - x
			if line[j] == 1:
				ones[x] += 1
	sol = 0
	for i in range((n + m - 1) // 2):
		tot = 2 * min(i + 1, n, m)
		sol += min(ones[i], tot - ones[i])
	print(sol)


import sys
input = lambda : sys.stdin.readline().rstrip()
t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	Z = [0] * (n + m - 1)
	O = [0] * (n + m - 1)
	for i in range(n):
		A = [int(j) for j in input().split()]
		for (j, a) in enumerate(A):
			if a == 0:
				Z[i + j] += 1
			else:
				O[i + j] += 1
	ans = 0
	for i in range((n + m - 1) // 2):
		(x, y) = (Z[i] + Z[n + m - 2 - i], O[i] + O[n + m - 2 - i])
		ans += min(x, y)
	print(ans)


tests = int(input())
for test in range(tests):
	(rows, cols) = map(int, input().split())
	a = []
	for i in range(rows):
		b = list(map(int, input().split()))
		a.append(b)
	cnt = [[0 for j in range(2)] for i in range(rows + cols)]
	for r in range(rows):
		for c in range(cols):
			if r + c != rows + cols - r - c - 2:
				cnt[min(r + c, rows + cols - r - c - 2)][a[r][c]] += 1
	res = 0
	for i in cnt:
		res += min(i[0], i[1])
	print(res)


from sys import stdin
inp = lambda : stdin.readline().strip()
t = int(inp())
for _ in range(t):
	(n, m) = [int(x) for x in inp().split()]
	adj = []
	for i in range(n):
		adj.append([int(x) for x in inp().split()])
	ansFrom = [[0, 0] for x in range((n + m) // 2)]
	flag = 0
	if (n + m) % 2 == 0:
		flag = 1
	else:
		flag = 0
	for i in range(n):
		for j in range(m):
			if i + j < (n + m) // 2:
				ansFrom[i + j][adj[i][j]] += 1
			else:
				ansFrom[(n + m) // 2 - 1 - (i + j - (n + m) // 2) - flag][adj[i][j]] += 1
	ans = 0
	if (n + m) % 2 == 1:
		for (i, j) in ansFrom:
			ans += min(i, j)
	else:
		for (i, j) in ansFrom[:-1]:
			ans += min(i, j)
	print(ans)


def main():
	t = int(input())
	for _ in range(t):
		(n, m) = map(int, input().split())
		l = []
		total = 0
		for __ in range(n):
			l.append(input().split())
		starting_pts = []
		for i in range(m):
			starting_pts.append((0, i))
		for j in range(1, n):
			starting_pts.append((j, m - 1))
		for idx in range((n + m - 1) // 2):
			sp1 = starting_pts[idx]
			sp2 = starting_pts[-(idx + 1)]
			delta = 0
			sp1s = [0, 0]
			sp2s = [0, 0]
			while sp1[0] + delta < n and sp1[1] - delta >= 0:
				sq1 = l[sp1[0] + delta][sp1[1] - delta]
				sp1s[int(sq1)] += 1
				sq2 = l[sp2[0] + delta][sp2[1] - delta]
				sp2s[int(sq2)] += 1
				delta += 1
			total_0s = sp1s[0] + sp2s[0]
			total_1s = sp1s[1] + sp2s[1]
			total += min(total_0s, total_1s)
		print(total)
main()


import sys

def arr():
	return list(map(int, input().split()))
input = sys.stdin.readline
from collections import defaultdict
import math
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	grid = []
	for i in range(n):
		grid.append(arr())
	ans = 0
	d = [[grid[i][x - i] for i in range(x + 1) if i < n and x - i < m] for x in range(n + m - 1)]
	for i in range(len(d) // 2):
		t = d[i]
		x = d[-(i + 1)]
		count1 = 0
		count2 = 0
		for j in range(len(d[i])):
			if t[j] == 0:
				count1 += 1
			if x[j] == 0:
				count2 += 1
		ones = 2 * len(t) - count1 - count2
		zeroes = count1 + count2
		ans += min(2 * len(t) - ones, 2 * len(t) - zeroes)
	print(ans)


from math import ceil
for _ in range(int(input())):
	(n, m) = list(map(int, input().split()))
	a = [[int(j) for j in input().split()] for _ in range(n)]
	len_path = n + m - 2
	half = ceil(len_path / 2)
	dp = {}
	for i in range(n):
		for j in range(m):
			dist = i + j
			if dist >= half:
				dist = len_path - (i + j)
			if dist == half:
				continue
			if dist not in dp:
				dp[dist] = [0, 0]
			dp[dist][a[i][j]] += 1
	c = 0
	for (zero, one) in dp.values():
		c += min(zero, one)
	print(c)


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	al = [list(map(int, input().split())) for i in range(n)]
	l = n + m - 1
	c0 = [0] * l
	c1 = [0] * l
	for (i, row) in enumerate(al):
		for (j, a) in enumerate(row):
			if a == 0:
				c0[i + j] += 1
			else:
				c1[i + j] += 1
	m = l // 2
	ans = 0
	for i in range(m):
		a0 = c0[i] + c0[-i - 1]
		a1 = c1[i] + c1[-i - 1]
		ans += min(a0, a1)
	print(ans)


t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	mat = [list(map(int, input().split())) for __ in range(n)]
	d = n + m - 2
	cnt = 0
	for i in range((n + m - 1) // 2):
		(one, zero) = (0, 0)
		for j in range(max(0, i + 1 - m), min(i, n - 1) + 1):
			if mat[j][i - j] == 0:
				zero += 1
			else:
				one += 1
		for j in range(max(0, d - i + 1 - m), min(d - i, n - 1) + 1):
			if mat[j][d - i - j] == 0:
				zero += 1
			else:
				one += 1
		cnt += min(one, zero)
	print(cnt)


t = int(input())
for l in range(t):
	(n, m) = input().split()
	n = int(n)
	m = int(m)
	mat = []
	for k in range(n):
		mat.append(list(map(int, input().split())))
	s = [0, 0]
	e = [n - 1, m - 1]
	res = 0
	max_steps = n + m - 1
	steps = 0
	while steps < max_steps // 2:
		count = {0: 0, 1: 0}
		c_i = s[0]
		c_j = s[1]
		while c_i < n and c_j >= 0:
			count[mat[c_i][c_j]] += 1
			c_i += 1
			c_j -= 1
		c_i = e[0]
		c_j = e[1]
		while c_i >= 0 and c_j < m:
			count[mat[c_i][c_j]] += 1
			c_i -= 1
			c_j += 1
		if count[0] >= count[1]:
			res += count[1]
		else:
			res += count[0]
		if s[1] < m - 1:
			s[1] += 1
		else:
			s[0] += 1
		if e[1] >= 1:
			e[1] -= 1
		else:
			e[0] -= 1
		steps += 1
	print(res)


from sys import stdin
for _ in range(int(stdin.readline())):
	(n, m) = map(int, stdin.readline().split())
	maps = []
	ans = 0
	totals = [0] * (n + m - 1)
	ones = [0] * (n + m - 1)
	zeros = [0] * (n + m - 1)
	for i in range(n):
		array = list(map(int, stdin.readline().split()))
		for j in range(m):
			totals[i + j] += 1
			if array[j] == 1:
				ones[i + j] += 1
			else:
				zeros[i + j] += 1
	for i in range((n + m - 1) // 2):
		ans += min(ones[i] + ones[n + m - 2 - i], zeros[i] + zeros[n + m - 2 - i])
	print(ans)


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	ar = []
	for i in range(n):
		ar.append([int(x) for x in input().split()])
	temp = []
	for i in range(n + m):
		temp.append([0, 0])
	for i in range(n):
		for j in range(m):
			temp[i + j][ar[i][j]] += 1
	ans = 0
	for i in range(n + m - 1):
		j = n + m - 2 - i
		if i >= j:
			continue
		ans += min(temp[i][0] + temp[j][0], temp[i][1] + temp[j][1])
	print(ans)


t = int(input())
from collections import Counter, defaultdict
for __ in range(t):
	(n, m) = map(int, input().split())
	arr = []
	for row_num in range(n):
		arr.append(list(map(int, input().split())))
	d_levels = defaultdict(list)
	for i in range(n):
		for j in range(m):
			if i + j == n + m - 2 - (i + j):
				continue
			level = min(i + j, n + m - 2 - (i + j))
			d_levels[level].append(arr[i][j])
	total_cost = 0
	for (d_level, d_list) in d_levels.items():
		c = Counter(d_list)
		(most_common_value, most_common_count) = c.most_common(1)[0]
		cost = len(d_list) - most_common_count
		total_cost += cost
	print(total_cost)


from collections import defaultdict
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	mat = []
	r = defaultdict(list)
	for i in range(n):
		mat.append(list(map(int, input().split())))
		for j in range(m):
			r[i + j].append(mat[i][j])
	num = len(r.keys())
	ans = 0
	for i in range(num // 2):
		z = r[i].count(0) + r[num - 1 - i].count(0)
		o = r[i].count(1) + r[num - 1 - i].count(1)
		ans += min(o, z)
	print(ans)


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	l = []
	for _ in range(n):
		l.append(list(map(int, input().split())))
	sol = 0
	for i in range((n + m - 1) // 2):
		(one, zero) = (0, 0)
		for j in range(i + 1):
			if j < n and i - j < m:
				if l[j][i - j] == 0:
					zero += 1
				else:
					one += 1
				if l[n - 1 - j][m - 1 - (i - j)] == 0:
					zero += 1
				else:
					one += 1
		sol += min(zero, one)
	print(sol)


T = range(int(input()))
for t in T:
	(N, M) = map(int, input().split(' '))
	matrix = []
	for j in range(N):
		row = list(map(int, input().split(' ')))
		matrix.append(row)
	q_start = set()
	q_start.add((0, 0))
	q_end = set()
	q_end.add((N - 1, M - 1))
	count = 1
	ans = 0
	while count <= (N + M - 1) // 2:
		n0 = 0
		n1 = 0
		newq_start = set()
		for pos in q_start:
			(x, y) = pos
			if x >= N or y >= M:
				continue
			if matrix[x][y] == 1:
				n1 += 1
			else:
				n0 += 1
			newq_start.add((x, y + 1))
			newq_start.add((x + 1, y))
		newq_end = set()
		for pos in q_end:
			(x, y) = pos
			if x < 0 or y < 0:
				continue
			if matrix[x][y] == 1:
				n1 += 1
			else:
				n0 += 1
			newq_end.add((x, y - 1))
			newq_end.add((x - 1, y))
		ans += min(n0, n1)
		q_start = newq_start
		q_end = newq_end
		count += 1
	print(ans)


import sys
input = sys.stdin.buffer.readline

def prog():
	for _ in range(int(input())):
		(n, m) = map(int, input().split())
		matrix = [list(map(int, input().split())) for i in range(n)]
		if n > m:
			new_matrix = [[0 for i in range(n)] for i in range(m)]
			for i in range(n):
				for j in range(m):
					new_matrix[j][i] = matrix[i][j]
			matrix = new_matrix
			a = n
			n = m
			m = a
		change = 0
		for j in range((m + n - 3) // 2 + 1):
			i = 0
			j = j
			i2 = n - 1
			j2 = m - 1 - j
			zeros = 0
			ones = 0
			while i < n and 0 <= j:
				if matrix[i][j] == 0:
					zeros += 1
				else:
					ones += 1
				i += 1
				j -= 1
			while 0 <= i2 and j2 < m:
				if matrix[i2][j2] == 0:
					zeros += 1
				else:
					ones += 1
				i2 -= 1
				j2 += 1
			change += min(zeros, ones)
		print(change)
prog()


for o in range(int(input())):
	(a, b) = map(int, input().split())
	s = [list(map(int, input().split())) for i in range(a)]
	d = a + b - 1
	S = [[] for i in range(d)]
	res = 0
	for i in range(a):
		for j in range(b):
			S[i + j].append(s[i][j])
	for i in range(d // 2):
		v = S[i] + S[-1 - i]
		res += min(v.count(0), v.count(1))
	print(res)


tt = int(input())
for loop in range(tt):
	(n, m) = map(int, input().split())
	z = [0] * ((n + m - 1) // 2)
	o = [0] * ((n + m - 1) // 2)
	for i in range(n):
		a = list(map(int, input().split()))
		for j in range(m):
			d = min(i + j, n - i - 1 + m - j - 1)
			if d < len(z):
				if a[j] == 0:
					z[d] += 1
				else:
					o[d] += 1
	ans = 0
	for i in range(len(z)):
		ans += min(o[i], z[i])
	print(ans)


t = int(input())
for f in range(t):
	(n, m) = map(int, input().split())
	a = []
	ans = []
	for i in range(n):
		a.append(list(map(int, input().split())))
	for k in range(n):
		c1 = 0
		c2 = 0
		for i in range(min(k + 1, m)):
			if a[k - i][i] == 0:
				c1 += 1
			else:
				c2 += 1
		ans.append([c1, c2])
	for k in range(1, m):
		c1 = 0
		c2 = 0
		for i in range(k, min(m, n + k)):
			if a[n + k - 1 - i][i] == 0:
				c1 += 1
			else:
				c2 += 1
		ans.append([c1, c2])
	ns = 0
	for i in range(len(ans) // 2):
		ns += min(ans[i][0] + ans[len(ans) - 1 - i][0], ans[i][1] + ans[len(ans) - 1 - i][1])
	print(ns)


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	ans = 0
	g = {}
	for i in range(n):
		s = list(map(int, input().split()))
		for j in range(m):
			if not g.get(i + j):
				g[i + j] = [0, 0]
			g[i + j][s[j]] += 1
	k = n + m - 1
	for i in range(k):
		if i != k - i - 1:
			ans += min(g[i][0] + g[k - i - 1][0], g[i][1] + g[k - i - 1][1])
	print(ans // 2)


for _ in range(int(input())):
	(n, m) = tuple(map(int, input().split()))
	largest_dist = (n + m) // 2
	if (n + m) % 2 == 0:
		largest_dist -= 1
	dist_dict = {dist: [0, 0] for dist in range(largest_dist)}
	for i in range(1, n + 1):
		row = list(map(int, input().split()))
		for j in range(1, m + 1):
			dist = min(i + j - 2, m + n - i - j)
			if dist < largest_dist:
				dist_dict[dist][row[j - 1]] += 1
	print(sum((min(dist) for dist in dist_dict.values())))


t = int(input())
for k in range(0, t):
	(n, m) = map(int, input().split())
	a = []
	for i in range(0, n):
		s = list(map(int, input().split()))
		a.append(s)
	ans = [0] * 100
	ans1 = [0] * 100
	f = 0
	for i in range(0, n):
		for j in range(0, m):
			if a[i][j] == 0:
				ans[i + j] = ans[i + j] + 1
			else:
				ans1[i + j] = ans1[i + j] + 1
	if (n + m) % 2 == 0:
		p = (n + m - 2) // 2
	else:
		p = (n + m - 1) // 2
	for i in range(0, p):
		f = f + min(ans[i] + ans[n + m - 2 - i], ans1[i] + ans1[n + m - 2 - i])
	print(f)


T = int(input())

def cost(dist_map):
	N = len(dist_map)
	HALF = N // 2
	res = 0
	for (i, (a, b)) in enumerate(dist_map[:HALF]):
		(sa, sb) = dist_map[N - 1 - i]
		a += sa
		b += sb
		res += min(a, b)
	return res

def solve():
	(N, M) = [int(x) for x in input().split()]
	A = []
	for _ in range(N):
		A.append([int(x) for x in input().split()])
	dist_map = []
	for d in range(N + M - 1):
		num = [0, 0]
		for i in range(N):
			j = d - i
			if 0 <= j < M:
				num[A[i][j]] += 1
		dist_map.append(num)
	print(cost(dist_map))
for _ in range(T):
	solve()


from collections import deque

def check(i, j):
	if 0 <= i < n and 0 <= j < m:
		return True
	return False
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	ls = []
	for i in range(n):
		ls.append(list(map(int, input().split())))
	group = [[0, 0] for i in range(m + n)]
	for i in range(n):
		for j in range(m):
			group[i + j][ls[i][j]] += 1
	cnt = 0
	for i in range(n + m - 1):
		j = n + m - 2 - i
		if i >= j:
			continue
		cnt += min(group[i][0] + group[j][0], group[i][1] + group[j][1])
	print(cnt)


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, ceil
from collections import Counter, defaultdict, deque
from heapq import heapify, heappop, heappush

def main():
	for _ in range(N()):
		(n, m) = RL()
		arr = [RLL() for _ in range(n)]
		num = n + m - 2
		rec = [[] for _ in range(num + 1)]
		q = deque()
		q.append((0, 0, 0))
		vis = [[0] * m for _ in range(n)]
		nex = [[1, 0], [0, 1]]
		while q:
			(x, y, d) = q.popleft()
			rec[d].append(arr[x][y])
			for (nx, ny) in nex:
				(xx, yy) = (nx + x, ny + y)
				if -1 < xx < n and -1 < yy < m and (vis[xx][yy] == 0):
					q.append((xx, yy, d + 1))
					vis[xx][yy] = 1
		res = 0
		for i in range(ceil(num / 2)):
			(l1, l2) = (len(rec[i]), len(rec[num - i]))
			(o1, o2) = (rec[i].count(1), rec[num - i].count(1))
			zero = l1 + l2 - o1 - o2
			res += min(o1 + o2, zero)
		print(res)
main()


def problem1():
	(a, b) = list(map(int, input().split()))
	if b > a:
		b = b + a
		a = b - a
		b = b - a
	if a * b < 2:
		print(0)
	elif a >= 2 * b:
		print(b)
	else:
		print(a - b + 2 * (2 * b - a) // 3)

def problem2():
	(n, x, m) = list(map(int, input().split()))
	a = x
	b = x
	for _ in range(m):
		(l, r) = list(map(int, input().split()))
		if l < a and r >= a:
			a = l
		if r > b and l <= b:
			b = r
	print(b - a + 1)

def problem3():
	(n, m) = list(map(int, input().split()))
	a = []
	b = [0] * ((n + m - 1) // 2)
	c = [0] * ((n + m - 1) // 2)
	for _ in range(n):
		a.append(list(map(int, input().split())))
	for i in range(n):
		for j in range(m):
			if i + j == (n + m - 1) // 2 and (n + m) % 2 == 0:
				continue
			b[min(i + j, n + m - 2 - i - j)] += a[i][j]
			c[min(i + j, n + m - 2 - i - j)] += 1
	s = 0
	for i in range(len(b)):
		s += min(b[i], c[i] - b[i])
	print(s)
cases = int(input())
for _ in range(cases):
	problem3()


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

def inin():
	return int(input())

def inar():
	return list(map(int, input().split()))

def ar(element, size):
	return [element for i in range(size)]

def yes():
	print('Yes')

def no():
	print('No')
Testcase = inin()
for _ in range(Testcase):
	(n, m) = inar()
	graph = [[] for i in range(n)]
	for i in range(n):
		graph[i] = inar()
	dist1 = [0 for i in range(n + m)]
	dist0 = [0 for i in range(n + m)]
	for i in range(n):
		for j in range(m):
			dist = i + j + 1
			if graph[i][j] == 0:
				dist0[dist] += 1
			else:
				dist1[dist] += 1
	su = 0
	for k in range(1, (n + m - 1) // 2 + 1):
		pk = n + m - k
		su += min(dist0[k] + dist0[pk], dist1[k] + dist1[pk])
	print(su)


from sys import setrecursionlimit, stdin
import math
setrecursionlimit(10 ** 5)
readline = stdin.readline
for _ in range(int(readline().rstrip())):
	(n, m) = map(int, readline().split())
	temp_list = []
	grid = [list(map(int, readline().split())) for _ in range(n)]
	(countzero, countone) = ([0] * (n + m - 1), [0] * (n + m - 1))
	ans = 0
	for i in range(n):
		for j in range(m):
			if not grid[i][j]:
				countzero[i + j] += 1
			else:
				countone[i + j] += 1
	if (n + m) % 2 == 0:
		v = (n - 1 + m - 1) // 2
	else:
		v = (n - 1 + m - 1 + 1) // 2
	for i in range(v):
		zeroes = countzero[i] + countzero[n - 1 + m - 1 - i]
		ones = countone[i] + countone[n - 1 + m - 1 - i]
		ans += min(zeroes, ones)
	print(ans)


from collections import defaultdict
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	a = []
	for i in range(n):
		a.append(list(map(int, input().split())))
	d = defaultdict(lambda : [])
	for i in range(n):
		for j in range(m):
			d[i + j].append(a[i][j])
	x = len(d)
	(i, j) = (0, x - 1)
	ans = 0
	while j > i:
		lst = d[i] + d[j]
		zero = lst.count(0)
		one = lst.count(1)
		ans += min(zero, one)
		i += 1
		j -= 1
	print(ans)


for _ in range(int(input())):
	(a, b) = map(int, input().split())
	c = []
	for i in range(a):
		d = list(map(int, input().split()))
		for j in range(b):
			if i + j != a + b - 2 - (i + j):
				c.append((d[j], min(i + j, a + b - 2 - (i + j))))
	print(sum([min((c.count((0, i)), c.count((1, i)))) for i in range((a + b - 2) // 2 + 1)]))


from collections import defaultdict as dd
import math
import sys
input = sys.stdin.readline

def nn():
	return int(input())

def li():
	return list(input())

def mi():
	return list(map(int, input().split()))

def lm():
	return list(map(int, input().split()))
q = nn()
for _ in range(q):
	(n, m) = mi()
	mat = []
	for i in range(n):
		row = lm()
		mat.append(row)
	zeros = [0] * (n + m - 1)
	ones = [0] * (n + m - 1)
	for i in range(n):
		for j in range(m):
			if mat[i][j] == 1:
				ones[i + j] += 1
			else:
				zeros[i + j] += 1
	ops = 0
	for i in range((m + n - 1) // 2):
		ops += min(zeros[i] + zeros[-i - 1], ones[i] + ones[-i - 1])
	print(ops)


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 ** 2)

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))))
from collections import deque, defaultdict
import heapq

def solution(a, n, m):
	d = defaultdict(lambda : defaultdict(int))
	for line in range(1, n + m):
		start_col = max(0, line - n)
		count = min(line, m - start_col, n)
		for j in range(0, count):
			if (n + m) % 2 == 1 or min(n, line) - 1 + start_col != (n + m - 2) // 2:
				d[min(min(n, line) - 1 + start_col, n + m - 2 - (min(n, line) - 1 + start_col))][a[min(n, line) - j - 1][start_col + j]] += 1
	sol = 0
	for key in d:
		sol += min(d[key][0], d[key][1])
	return sol

def main():
	T = ri()
	for i in range(T):
		(n, m) = ria()
		a = []
		for _ 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()


import sys, math
from collections import deque

def solve():
	(n, m) = map(int, input().split())
	A = []
	for i in range(n):
		A.append(list(map(int, input().split())))
	H = (n + m - 1) // 2
	cnt = [[0 for _ in range(3)] for _ in range(H)]
	for i in range(n):
		for j in range(m):
			k = i + j
			if (n + m - 1) % 2 == 1 and H == k:
				continue
			if k >= H:
				k = n + m - 1 - k - 1
			cnt[k][A[i][j]] += 1
			cnt[k][2] += 1
	total = 0
	for i in range(H):
		total += min(cnt[i][2] - cnt[i][1], cnt[i][2] - cnt[i][0])
	print(total)
	return
for _ in range(int(input())):
	solve()


t = int(input())
for _ in range(t):
	(n, m) = [int(x) for x in input().split()]
	mat = []
	for i in range(n):
		s = list(map(int, input().split()))
		mat.append(s)
	l = []
	for i in range(0, n + m):
		l.append([0, 0])
	for i in range(n):
		for j in range(m):
			if mat[i][j] == 0:
				l[i + j + 1][0] += 1
			else:
				l[i + j + 1][1] += 1
	a = 1
	b = n + m - 1
	ans = 0
	while a < b:
		zero = l[a][0] + l[b][0]
		one = l[a][1] + l[b][1]
		ans += min(zero, one)
		a += 1
		b -= 1
	print(ans)


t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	arr = []
	for i in range(n):
		tarr = list(map(int, input().split()))
		arr.append(tarr)
	dist = n + m - 2
	x = (dist + 1) // 2
	arra = [[] for i in range(x)]
	ans = 0
	for i in range(n):
		for j in range(m):
			dst = min(i + j, n + m - 2 - i - j)
			if dst == x:
				continue
			arra[dst].append(arr[i][j])
	for i in range(len(arra)):
		tlen = len(arra[i])
		ans += min(tlen - sum(arra[i]), sum(arra[i]))
	print(ans)


def solve():
	(n, m) = map(int, input().split())
	k = n + m - 1
	dd = [[] for i in range(k)]
	tb = [list(map(int, input().split())) for i in range(n)]
	for x in range(n):
		for y in range(m):
			dd[x + y].append(tb[x][y])
	ans = 0
	for i in range(k // 2):
		n1 = len(dd[i]) + len(dd[k - i - 1])
		n2 = sum(dd[i]) + sum(dd[k - i - 1])
		ans += min(n2, n1 - n2)
	print(ans)
for i in range(int(input())):
	solve()


from collections import defaultdict as dd
from collections import deque
import bisect
import heapq

def ri():
	return int(input())

def rl():
	return list(map(int, input().split()))

def solve():
	(n, m) = rl()
	steps = n + m - 2
	half = steps // 2
	mat = []
	for i in range(n):
		mat.append(rl())
	ones = dd(int)
	zeros = dd(int)
	for i in range(n):
		for j in range(m):
			diag = i + j
			if diag > half:
				diag = steps - diag
			if mat[i][j] == 1:
				ones[diag] += 1
			else:
				zeros[diag] += 1
	answer = 0
	for diag in range(half + 1):
		if (n + m) % 2 == 0 and diag == half:
			continue
		o = ones[diag]
		z = zeros[diag]
		answer += min(o, z)
	print(answer)
mode = 'T'
if mode == 'T':
	t = ri()
	for i in range(t):
		solve()
else:
	solve()


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	ans = [[] for i in range(n + m - 1)]
	c = 0
	mat = [list(map(int, input().split())) for i in range(n)]
	for i in range(n):
		for j in range(m):
			ans[i + j].append(mat[i][j])
	for j in range((n + m - 1) // 2):
		s = ans[j] + ans[-1 - j]
		c += min(s.count(1), s.count(0))
	print(c)


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	d = {}
	for i in range(n):
		for (r, val) in enumerate(map(int, input().split())):
			if d.get(min(r + i, m + n - 2 - r - i)):
				d[min(r + i, m + n - 2 - r - i)][val] += 1
			else:
				d[min(r + i, m + n - 2 - r - i)] = [val == 0, val == 1]
	ans = 0
	for i in d.values():
		ans += min(i)
	if (m + n) % 2 == 0:
		ans -= min(d[(m + n - 2) // 2])
	print(ans)


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	d = []
	for _ in range(n):
		d.append(list(map(int, input().split())))
	cnt = []
	for i in range(n + m - 1):
		cnt.append([0] * 2)
	for i in range(n):
		for j in range(m):
			cnt[i + j][d[i][j]] += 1
	ans = 0
	for i in range(n + m - 1):
		if i >= n + m - 2 - i:
			break
		ans += min(cnt[i][0] + cnt[-i - 1][0], cnt[i][1] + cnt[-i - 1][1])
	print(ans)


visited = []
n = 0
m = 0

def canRight(c):
	return c[1] != m - 1

def canDown(c):
	return c[0] != n - 1

def canLeft(c):
	return c[1] != 0

def canUP(c):
	return c[0] != 0

def getNext(current):
	ans = []
	if canRight(current):
		ans.append([current[0], current[1] + 1])
	if canDown(current):
		ans.append([current[0] + 1, current[1]])
	return ans

def getNextInv(current):
	ans = []
	if canLeft(current):
		ans.append([current[0], current[1] - 1])
	if canUP(current):
		ans.append([current[0] - 1, current[1]])
	return ans
t = int(input())
for _ in range(t):
	(n, m) = [int(x) for x in input().split()]
	arr = []
	for _ in range(n):
		arr.append([int(x) for x in input().split()])
	ans = 0
	added = [[0 for i in range(m)] for j in range(n)]
	bfs1 = [[0, 0]]
	bfs2 = [[n - 1, m - 1]]
	while 1:
		zeros = 0
		ones = 0
		s = len(bfs1)
		while s > 0:
			s -= 1
			current = bfs1.pop(0)
			if arr[current[0]][current[1]] == 1:
				ones += 1
			else:
				zeros += 1
			for ne in getNext(current):
				if added[ne[0]][ne[1]] == 0:
					bfs1.append(ne)
					added[ne[0]][ne[1]] = 1
		s = len(bfs2)
		if s == 0:
			break
		while s > 0:
			s -= 1
			current = bfs2.pop(0)
			if arr[current[0]][current[1]] == 1:
				ones += 1
			else:
				zeros += 1
			for ne in getNextInv(current):
				if added[ne[0]][ne[1]] == 0:
					bfs2.append(ne)
					added[ne[0]][ne[1]] = 1
		ans += min(zeros, ones)
	print(ans)


import os
import sys
from io import BytesIO, IOBase
import threading

def main():
	for _ in range(int(input())):
		(n, m) = map(int, input().split())
		grid = []
		for i in range(n):
			grid.append(list(map(int, input().split())))
		visited = [[0] * (m + 1) for _ in range(n + 1)]
		old_a = [(1, 1), (n, m)]
		visited[1][1] = 1
		visited[n][m] = 1
		delta = [(1, 0), (0, 1), (-1, 0), (0, -1)]
		ans = 0
		while True:
			cnt_0 = 0
			cnt_1 = 0
			new_a = []
			for (x, y) in old_a:
				for (dx, dy) in delta:
					n_x = x + dx
					n_y = y + dy
					if 1 <= n_x <= n and 1 <= n_y <= m and (visited[n_x][n_y] == 0):
						new_a.append((n_x, n_y))
						visited[n_x][n_y] = 1
				if grid[x - 1][y - 1] == 1:
					cnt_1 += 1
				else:
					cnt_0 += 1
			old_a = new_a
			if len(old_a) == 0:
				if (n % 2 + m % 2) % 2 == 1:
					ans += min(cnt_0, cnt_1)
				break
			else:
				ans += min(cnt_0, cnt_1)
		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()


for i in range(int(input())):
	(n, m) = map(int, input().split())
	mat = []
	for j in range(n):
		arr = list(map(int, input().split()))
		mat.append(arr)
	mid = (m + n - 1) // 2
	k = 0
	ans = 0
	fir_row = 0
	fir_col = 0
	last_row = n - 1
	last_col = m - 1
	while k < mid:
		one = 0
		zero = 0
		temp_row = fir_row
		temp_col = fir_col
		while temp_row < n and temp_col >= 0:
			if mat[temp_row][temp_col] == 0:
				zero += 1
			else:
				one += 1
			temp_row += 1
			temp_col -= 1
		temp_row = last_row
		temp_col = last_col
		while temp_row < n and temp_col >= 0:
			if mat[temp_row][temp_col] == 0:
				zero += 1
			else:
				one += 1
			temp_row += 1
			temp_col -= 1
		ans += min(one, zero)
		if fir_col < m - 1:
			fir_col += 1
		else:
			fir_row += 1
		if last_row > 0:
			last_row -= 1
		else:
			last_col -= 1
		k += 1
	print(ans)


import sys
reader = (s.rstrip() for s in sys.stdin)
input = reader.__next__

def gift():
	for _ in range(t):
		(n, m) = list(map(int, input().split()))
		if n <= m:
			seq = []
			for i in range(n):
				tisrow = list(map(int, input().split()))
				seq.append(tisrow)
		else:
			seq = []
			for j in range(m):
				seq.append([])
			for i in range(n):
				tisrow = list(map(int, input().split()))
				for j in range(m):
					seq[j].append(tisrow[j])
			(n, m) = (m, n)
		basenum = (n + m - 1) // 2
		oddcheck = (n + m - 1) % 2
		totcheck = basenum + oddcheck
		ans = 0
		for i in range(totcheck):
			if i == basenum:
				continue
			else:
				farray = []
				barray = []
				spoint = [0, i]
				epoint = [n - 1, m - 1 - i]
				if i < n:
					roundlen = i + 1
				else:
					roundlen = n
				for j in range(roundlen):
					(s, e) = spoint
					farray.append(seq[s][e])
					spoint = [s + 1, e - 1]
					(s1, e1) = epoint
					barray.append(seq[s1][e1])
					epoint = [s1 - 1, e1 + 1]
				c1 = 0
				c0 = 0
				for ele in farray:
					if ele:
						c1 += 1
					else:
						c0 += 1
				for ele in barray:
					if ele:
						c1 += 1
					else:
						c0 += 1
				if c1 == 0 or c0 == 0:
					continue
				else:
					ans += min(c1, c0)
		yield ans
t = int(input())
ans = gift()
print(*ans, sep='\n')


import math
import time
from collections import defaultdict, deque
from sys import stdin, stdout
from bisect import bisect_left, bisect_right, bisect
t = int(input())
for _ in range(t):
	(n, m) = map(int, stdin.readline().split())
	arr = [[0, 0] for _ in range(n + m)]
	grid = []
	for _ in range(n):
		grid.append(list(map(int, stdin.readline().split())))
	for i in range(n):
		for j in range(m):
			x = min(i + j, n + m - 2 - i - j)
			if grid[i][j] == 0:
				arr[x][0] += 1
			else:
				arr[x][1] += 1
	ans = 0
	if (n + m - 1) % 2 == 0:
		for (i, j) in arr:
			ans += min(i, j)
	else:
		for i in range(n + m):
			if i != (n + m) // 2 - 1:
				ans += min(arr[i][0], arr[i][1])
	print(ans)


t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	L = [[int(l) for l in input().split()] for _ in range(n)]
	c = (n + m - 2) // 2
	if (n + m) % 2 == 0:
		c -= 1
	num = [[0, 0] for _ in range(c + 1)]
	for i in range(n):
		for j in range(m):
			idx = min(i + j, n + m - 2 - i - j)
			if idx > c:
				continue
			num[idx][L[i][j]] += 1
	ans = 0
	for t in num:
		ans += min(t)
	print(ans)


import sys

def rs():
	return sys.stdin.readline().rstrip()

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

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

def ws(s):
	sys.stdout.write(s + '\n')

def wi(n):
	sys.stdout.write(str(n) + '\n')

def wia(a):
	sys.stdout.write(' '.join([str(x) for x in a]) + '\n')

def solve(n, m, a):
	k = (n + m - 1) // 2
	ones = [0] * k
	zeros = [0] * k
	for i in range(n):
		for j in range(m):
			if (n + m) % 2 == 0 and i + j == k:
				continue
			kk = i + j
			if kk >= k:
				kk = n - i - 1 + m - j - 1
			if a[i][j] == 0:
				zeros[kk] += 1
			else:
				ones[kk] += 1
	return sum([min(zeros[i], ones[i]) for i in range(k)])

def main():
	for _ in range(ri()):
		(n, m) = ria()
		a = []
		for _ in range(n):
			a.append(ria())
		wi(solve(n, m, a))
main()


T = int(input())
for t in range(T):
	(n, m) = map(int, input().split())
	arr = []
	for i in range(n):
		arr.append(list(map(int, input().split())))
	(start, end) = (2, n + m)
	ans = 0
	while start < end:
		(count0, count1) = (0, 0)
		if n > m:
			j = 1
			i = start - 1
			while i > 0 and j <= m:
				if arr[i - 1][j - 1] == 1:
					count1 += 1
				else:
					count0 += 1
				i -= 1
				j += 1
		else:
			i = 1
			j = start - 1
			while j > 0 and i <= n:
				if arr[i - 1][j - 1] == 1:
					count1 += 1
				else:
					count0 += 1
				i += 1
				j -= 1
		if n > m:
			j = m
			i = end - m
			while j > 0 and i <= n:
				if arr[i - 1][j - 1] == 1:
					count1 += 1
				else:
					count0 += 1
				i += 1
				j -= 1
		else:
			i = n
			j = end - n
			while i > 0 and j <= m:
				if arr[i - 1][j - 1] == 1:
					count1 += 1
				else:
					count0 += 1
				i -= 1
				j += 1
		ans += min(count0, count1)
		start += 1
		end -= 1
	print(ans)


def solution():
	(n, m) = list(map(int, input().split()))
	a = [list(map(int, input().split())) for i in range(n)]
	checked = [[0 for i in range(m)] for j in range(n)]
	count = 0
	l = n + m - 1
	fnext = []
	bnext = []
	fnext.append([0, 0])
	bnext.append([n - 1, m - 1])
	for i in range(l // 2):
		ones = 0
		zeros = 0
		nextf = []
		nextb = []
		while len(fnext) > 0:
			fi = fnext.pop()
			bi = bnext.pop()
			if a[fi[0]][fi[1]] == 0:
				zeros += 1
			else:
				ones += 1
			if a[bi[0]][bi[1]] == 0:
				zeros += 1
			else:
				ones += 1
			checked[fi[0]][fi[1]] = 1
			checked[bi[0]][bi[1]] = 1
			if fi[0] < n - 1 and checked[fi[0] + 1][fi[1]] != 1:
				nextf.append([fi[0] + 1, fi[1]])
				checked[fi[0] + 1][fi[1]] = 1
			if fi[1] < m - 1 and checked[fi[0]][fi[1] + 1] != 1:
				nextf.append([fi[0], fi[1] + 1])
				checked[fi[0]][fi[1] + 1] = 1
			if bi[0] > 0 and checked[bi[0] - 1][bi[1]] != 1:
				nextb.append([bi[0] - 1, bi[1]])
				checked[bi[0] - 1][bi[1]] = 1
			if bi[1] > 0 and checked[bi[0]][bi[1] - 1] != 1:
				nextb.append([bi[0], bi[1] - 1])
				checked[bi[0]][bi[1] - 1] = 1
		count += min(ones, zeros)
		fnext = nextf
		bnext = nextb
	print(count)
T = int(input())
for t in range(T):
	solution()


def solve():
	(n, m) = map(int, input().split())
	A = [list(map(int, input().split())) for _ in range(n)]
	if n > m:
		(n, m) = (m, n)
		A = list(zip(*A))
	T = []
	for i in range(n - 1):
		S = [0, 0]
		for j in range(i + 1):
			S[A[i - j][j]] += 1
		T.append(S)
	for i in range(m - n):
		S = [0, 0]
		for j in range(n):
			S[A[j][n - 1 + i - j]] += 1
		T.append(S)
	for i in range(n):
		S = [0, 0]
		for j in range(n - i):
			S[A[i + j][m - 1 - j]] += 1
		T.append(S)
	ret = 0
	for i in range((n + m - 1) // 2):
		zero = T[i][0] + T[-1 - i][0]
		one = T[i][1] + T[-1 - i][1]
		ret += min(one, zero)
	return ret

def main():
	T = int(input())
	for _ in range(T):
		print(solve())
main()


def nxt(x, y):
	if x == 0 or y == m - 1:
		return False
	return (x - 1, y + 1)
ans = []
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	u = []
	for i in range(n):
		u.append(list(map(int, input().split())))
	if n > m:
		u0 = []
		for i in range(m):
			u0.append([0] * n)
		for i in range(n):
			for j in range(m):
				u0[j][i] = u[i][j]
		u = u0[:]
		(n, m) = (m, n)
	ansi = 0
	for i in range((n + m - 1) // 2):
		if i < n:
			(x, y) = (i, 0)
		else:
			(x, y) = (n - 1, i - n + 1)
		z0 = 0
		z1 = 0
		if u[x][y] == 0:
			z0 += 1
		else:
			z1 += 1
		while nxt(x, y):
			(x, y) = nxt(x, y)
			if u[x][y] == 0:
				z0 += 1
			else:
				z1 += 1
		(x, y) = (n - 1, m - i - 1)
		if u[x][y] == 0:
			z0 += 1
		else:
			z1 += 1
		while nxt(x, y):
			(x, y) = nxt(x, y)
			if u[x][y] == 0:
				z0 += 1
			else:
				z1 += 1
		ansi += min(z0, z1)
	ans.append(ansi)
print('\n'.join(map(str, ans)))


import getopt
import sys
import math
onlyCase = -1
verbose = False
try:
	(opts, args) = getopt.getopt(sys.argv[1:], 'vc:', ['case='])
except getopt.GetoptError as err:
	print(str(err))
	sys.exit(2)
for (o, a) in opts:
	if o in ('-c', '--case'):
		onlyCase = int(a)
	elif o == '-v':
		verbose = True
	else:
		sys.exit()
ncases = int(input())
for c in range(1, ncases + 1):
	(N, M) = [int(x) for x in input().split()]
	A = []
	for i in range(N):
		A.append([int(x) for x in input().split()])
	if onlyCase != -1 and onlyCase != c:
		continue
	if verbose:
		print('%d x %d' % (N, M))
	B = [[0 for x in range(M)] for y in range(N)]
	for i in range(M):
		for j in range(N):
			B[j][i] = min(i + j, N + M - (2 + i + j))
	C = [[0, 0] for x in range((N + M) // 2)]
	for i in range(M):
		for j in range(N):
			if A[j][i] == 0:
				C[B[j][i]][0] += 1
			else:
				C[B[j][i]][1] += 1
	if verbose:
		print(A)
		print(B)
		print(C)
	if (N + M) % 2 == 0:
		C = C[:-1]
	count = 0
	for c in C:
		count += min(c[0], c[1])
	print('%d' % count)


import sys
input = sys.stdin.readline

def I():
	return input().strip()

def II():
	return int(input().strip())

def LI():
	return [*map(int, input().strip().split())]
import string, math, time, functools, random, fractions
from heapq import heappush, heappop, heapify
from bisect import bisect_left, bisect_right
from collections import deque, defaultdict, Counter, OrderedDict
from itertools import permutations, combinations, groupby
from operator import itemgetter
for _ in range(II()):
	(n, m) = LI()
	d = [[0, 0] for i in range(n + m - 1)]
	for i in range(n):
		inp = LI()
		for j in range(m):
			d[i + j][inp[j]] = d[i + j][inp[j]] + 1
	for i in range((n + m - 1) // 2):
		for j in range(2):
			d[i][j] = d[i][j] + d[n + m - 1 - 1 - i][j]
	ans = 0
	for i in range((n + m - 1) // 2):
		ans += min(d[i][0], d[i][1])
	print(ans)


def get_rows(grid):
	return [[c for c in r] for r in grid]

def get_cols(grid):
	return zip(*grid)

def print_diagonals(grid):
	b = [None] * (len(grid) - 1)
	grid = [b[:i] + r + b[i:] for (i, r) in enumerate(get_rows(grid))]
	return [[c for c in r if c is not None] for r in get_cols(grid)]
for _ in range(int(input())):
	(m, n) = map(int, input().split())
	le = [[int(i) for i in input().split()] for i in range(m)]
	l = print_diagonals(le)
	i = 0
	j = len(l) - 1
	ans = 0
	while i < j:
		a = l[i].count(1)
		b = l[j].count(1)
		tot1 = a + b
		tot0 = len(l[i]) + len(l[j]) - tot1
		an = min(tot1, tot0)
		ans += an
		i += 1
		j -= 1
	print(ans)


import math
t = int(input())

def travel_up(mat, n, m, r, c):
	temp = []
	while r >= 0 and c <= m - 1:
		temp.append(mat[r][c])
		r -= 1
		c += 1
	return temp

def count(x):
	c = len([xx for xx in x if xx == 1])
	return (len(x) - c, c)
for i in range(t):
	inp = input().split(' ')
	(n, m) = (int(inp[0]), int(inp[1]))
	mat = []
	for j in range(n):
		mat.append([int(x) for x in input().split(' ')])
	palind = []
	palind.append([mat[0][0]])
	for j in range(1, n):
		palind.append(travel_up(mat, n, m, j, 0))
	for j in range(1, m):
		palind.append(travel_up(mat, n, m, n - 1, j))
	changes = 0
	path_len = len(palind)
	for j in range(int(path_len / 2)):
		countl = count(palind[j])
		countr = count(palind[path_len - 1 - j])
		changes = changes + min(countl[0] + countr[0], countl[1] + countr[1])
	print(changes)


t = int(input())
for i in range(t):
	(n, m) = map(int, input().split())
	a = []
	for j in range(n):
		b = list(map(int, input().split()))
		a.append(b)
	l = n + m
	c = [[0, 0] for j in range(n + m)]
	for j in range(n):
		for p in range(m):
			c[j + p + 1][a[j][p]] += 1
	j = 1
	res = 0
	while j <= (l - 1) // 2:
		res += min(c[l - j][1] + c[j][1], c[l - j][0] + c[j][0])
		j += 1
	print(res)


t = int(input())
while t:
	t += -1
	(n, m) = map(int, input().split())
	l = []
	for i in range(n):
		tmp = list(map(int, input().split()))
		l.append(tmp)
	ans = 0
	boo = 0
	if (n + m) % 2 == 0:
		boo = (n + m) // 2
	else:
		boo = 1 + (n + m) // 2
	for i in range(1, boo):
		one = 0
		zero = 0
		for j in range(i):
			if 0 <= j < n and 0 <= i - j - 1 < m:
				if l[j][i - j - 1] == 0:
					zero -= -1
				else:
					one -= -1
			t1 = n - j - 1
			t2 = m - 1 - i + j + 1
			if 0 <= t1 < n and 0 <= t2 < m:
				if l[t1][t2] == 0:
					zero -= -1
				else:
					one -= -1
		ans += min(zero, one)
	print(ans)


T = int(input())
for _ in range(0, T):
	(n, m) = map(int, input().split())
	L = []
	for i in range(0, n):
		s = [int(x) for x in input().split()]
		L.append(s)
	tot = n + m - 1
	dp0 = [0] * tot
	dp1 = [0] * tot
	for i in range(n):
		for j in range(m):
			if L[i][j] == 0:
				dp0[i + j] += 1
			else:
				dp1[i + j] += 1
	ans = 0
	ln = len(dp0) // 2
	if len(dp0) % 2 != 0:
		ln += 1
	kk = len(dp0)
	for i in range(0, ln):
		c0 = dp0[i] + dp0[kk - i - 1]
		c1 = dp1[i] + dp1[kk - i - 1]
		if i != kk - i - 1:
			ans += min(c0, c1)
		else:
			ans += 0
	print(ans)


t = int(input())
for case in range(t):
	[n, m] = list(map(int, input().split()))
	a = []
	for i in range(n):
		a.append(list(map(int, input().split())))
	d = n + m - 2
	c = (n + m - 2) // 2
	ones = [0] * (c + 1)
	number = [0] * (c + 1)
	for i in range(n):
		for j in range(m):
			s = i + j
			if s <= c:
				ones[s] += a[i][j]
				number[s] += 1
			else:
				ones[d - s] += a[i][j]
				number[d - s] += 1
	for k in range(c + 1):
		ones[k] = min(ones[k], number[k] - ones[k])
	if (n + m - 2) % 2 == 0:
		ones[c] = 0
	print(sum(ones))


t = int(input())
krish = 1000
raj = krish * 1000
for i in range(t):
	ans = raj - 90090
	(n, m) = map(int, input().split())
	mt = []
	for _ in range(n):
		mt.append(list(map(int, input().split())))
	d = dict()
	step = [[0 for i in range(m)] for j in range(n)]
	step1 = [[0 for i in range(m)] for j in range(n)]
	d1 = dict()
	for i in range(n):
		for j in range(m):
			step[i][j] = i + j
			if i + j in d:
				d[i + j].append((i, j))
			else:
				d.update({i + j: [(i, j)]})
			step1[i][j] = n + m - 2 - i - j
			if n + m - 2 - i - j in d1:
				d1[n + m - 2 - i - j].append((i, j))
			else:
				d1.update({n + m - 2 - i - j: [(i, j)]})
	ans = 0
	for i in range((n + m - 1) // 2):
		cc = 0
		df = 0
		if d[i] == d1[i]:
			continue
		for j in d[i]:
			df += mt[j[0]][j[1]]
			cc += 1
		for j in d1[i]:
			df += mt[j[0]][j[1]]
			cc += 1
		ans += min(cc - df, df)
	print(ans)
	ans = ans + 800
	bc = 'Hello'


from math import *
t = int(input())
while t:
	t = t - 1
	(n, m) = map(int, input().split())
	a = []
	for i in range(n):
		c = list(map(int, input().split()))
		a.append(c)
	d = dict()
	for i in range(n):
		for j in range(m):
			x = min(i + j, n - i + m - j - 2)
			p = n - i - 1
			q = m - j - 1
			if p + q == i + j:
				continue
			o = d.get(x, [0, 0])
			o[a[i][j]] += 1
			d[x] = o
	out = 0
	for i in d.values():
		p = i[0]
		q = i[1]
		mx = max(p, q)
		mi = min(p, q)
		out += mi
	print(out)


import sys
import math
input = sys.stdin.readline
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	matrix = []
	for line in range(n):
		matrix.append([int(x) for x in input().split()])
	f = []
	for i in range(max(n, m) * 2 - 1):
		front = []
		for j in range(i + 1):
			x = j
			y = i - x
			try:
				front.append(matrix[x][y])
			except:
				pass
		if not front:
			break
		f.append(front)
	ans = 0
	for i in range(len(f) // 2):
		one = sum(f[i]) + sum(f[-i - 1])
		zero = len(f[i]) + len(f[-i - 1]) - one
		ans += min(one, zero)
	print(ans)


t = int(input())
for ii in range(t):
	(n, m) = map(int, input().split())
	mat = [list(map(int, input().split())) for i in range(n)]
	a = [[] for _ in range(n + m - 1)]
	for i in range(n):
		for j in range(m):
			a[i + j].append(mat[i][j])
	ans = 0
	for i in range((n + m - 1) // 2):
		pq = a[i] + a[-i - 1]
		ans += min(pq.count(0), pq.count(1))
	print(ans)


from sys import stdin, stdout
import sys
t = int(stdin.readline().strip())
for _ in range(t):
	(n, m) = stdin.readline().strip().split(' ')
	(n, m) = (int(n), int(m))
	mtr = []
	for i in range(n):
		mtr.append(list(map(int, stdin.readline().strip().split(' '))))
	dist = [[0, 0] for i in range(n + m - 1)]
	vis = [[False for i in range(m)] for j in range(n)]
	q = [(0, 0, 0)]
	while len(q) > 0:
		curr = q.pop(0)
		dist[curr[2]][mtr[curr[0]][curr[1]]] += 1
		if curr[0] + 1 < n and (not vis[curr[0] + 1][curr[1]]):
			q.append((curr[0] + 1, curr[1], curr[2] + 1))
			vis[curr[0] + 1][curr[1]] = True
		if curr[1] + 1 < m and (not vis[curr[0]][curr[1] + 1]):
			q.append((curr[0], curr[1] + 1, curr[2] + 1))
			vis[curr[0]][curr[1] + 1] = True
	ans = 0
	for i in range(len(dist) // 2):
		a = dist[i]
		b = dist[len(dist) - 1 - i]
		a[0] += b[0]
		a[1] += b[1]
		ans += min(a[0], a[1])
	stdout.write(str(ans) + '\n')


from sys import stdin, stdout
from collections import Counter
from math import ceil
from bisect import bisect_left
from bisect import bisect_right
import math

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

def ei():
	return map(int, stdin.readline().split())

def ip():
	return int(stdin.readline().strip())

def op(ans):
	return stdout.write(str(ans) + '\n')
for i in range(ip()):
	(n, m) = ei()
	v = []
	ans = [[0, 0] for i in range(70)]
	for i in range(n):
		v.append(ai())
	for i in range(n):
		for j in range(m):
			x = i + j
			y = n - 1 - i + (m - 1 - j)
			if x != y:
				ans[min(x, y)][v[i][j]] += 1
	final_ans = 0
	for i in range(70):
		final_ans += min(ans[i][0], ans[i][1])
	op(final_ans)


from sys import stdin, stdout
for query in range(int(stdin.readline())):
	nm = stdin.readline().split()
	n = int(nm[0])
	m = int(nm[1])
	matrix = []
	for row in range(n):
		matrix.append([int(x) for x in stdin.readline().split()])
	if (n + m - 1) % 2 == 0:
		mybool = True
		x = (n + m - 1) // 2
		numbers = [0] * x
		counts = [0] * x
	else:
		mybool = False
		x = (n + m + 1) // 2
		numbers = [0] * x
		counts = [0] * x
	for i in range(n):
		for j in range(m):
			if mybool:
				if i + j >= x:
					numbers[2 * x - (i + j + 1)] += 1
					counts[2 * x - (i + j + 1)] += matrix[i][j]
				else:
					numbers[i + j] += 1
					counts[i + j] += matrix[i][j]
			elif i + j >= x:
				numbers[2 * x - (i + j + 2)] += 1
				counts[2 * x - (i + j + 2)] += matrix[i][j]
			else:
				numbers[i + j] += 1
				counts[i + j] += matrix[i][j]
	total = 0
	if not mybool:
		x -= 1
	for y in range(x):
		total += min(counts[y], numbers[y] - counts[y])
	stdout.write(str(total) + '\n')


from sys import stdin
A = int(stdin.readline())
for k in range(0, A):
	B = list(map(int, stdin.readline().split()))
	n = B[0]
	m = B[1]
	C = list()
	for k in range(0, n):
		D = list(map(int, stdin.readline().split()))
		C.append(D)
	E = list()
	for t in range(0, m):
		sum = C[0][t]
		r = 0
		c = t
		while r < n - 1 and c > 0:
			r += 1
			c -= 1
			sum += C[r][c]
		E.append(sum)
	for u in range(1, n):
		sum = C[u][m - 1]
		r = u
		c = m - 1
		while r < n - 1 and c > 0:
			r += 1
			c -= 1
			sum += C[r][c]
		E.append(sum)
	MIN = min(m, n)
	count = 1
	ans = 0
	while len(E) > 0:
		if len(E) == 1:
			break
		elif count < MIN:
			RR = E[0] + E[len(E) - 1]
			ans += min(abs(2 * count - RR), RR)
		else:
			RR = E[0] + E[len(E) - 1]
			ans += min(abs(2 * MIN - RR), RR)
		count += 1
		E = E[1:len(E)]
		E = E[:len(E) - 1]
	print(ans)


T = int(input())
from collections import Counter
for _ in range(T):
	(n, m) = map(int, input().split())
	a = [[] for _ in range(n)]
	for i in range(n):
		a[i] = list(map(int, input().split()))
	ans = 0
	nn = (n + m - 1) // 2
	x = [[] for _ in range(n + m - 1)]
	for i in range(n):
		for j in range(m):
			x[i + j].append(a[i][j])
	for i in range(nn):
		b = Counter(x[i] + x[n + m - 2 - i])
		ans += min(b[0], b[1])
	print(ans)


from collections import defaultdict
for _ in range(int(input())):
	d = defaultdict(list)
	(n, m) = list(map(int, input().split()))
	a = []
	for _ in range(n):
		a.append(list(map(int, input().split())))
	for i in range(n):
		for j in range(m):
			if a[i][j] == 1:
				try:
					d[i + j][0] += 1
					d[i + j][1] += 1
				except:
					d[i + j] = [1, 1]
			else:
				try:
					d[i + j][0] += 1
				except:
					d[i + j] = [1, 0]
	i = 0
	s = 0
	j = m + n - 2
	while i < j:
		s += min(d[i][0] + d[j][0] - d[i][1] - d[j][1], d[i][1] + d[j][1])
		i += 1
		j -= 1
	print(s)


from sys import stdin, stdout
import math
from itertools import permutations, combinations
from collections import defaultdict
from bisect import bisect_left
from bisect import bisect_right

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

def In():
	return map(int, stdin.readline().split())

def I():
	return int(stdin.readline())
P = 1000000007

def main():
	for t in range(I()):
		(n, m) = In()
		arr = []
		sm = 0
		for i in range(n):
			lis = L()
			arr.append(lis)
		dict1 = {}
		for i in range((n + m - 1) // 2):
			dict1[i] = [0, 0]
		for i in range(n):
			for j in range(m):
				if min(i + j, n + m - i - j - 2) in dict1.keys():
					dict1[min(i + j, n + m - i - j - 2)][arr[i][j]] += 1
		for i in dict1.keys():
			sm += min(dict1[i][0], dict1[i][1])
		print(sm)
main()


T = int(input())
for t in range(T):
	(n, m) = list(map(int, input().split()))
	max_length = n + m - 2
	nbs = [[0, 0] for i in range(max_length + 1)]
	matrix = [input().split() for i in range(n)]
	for i in range(n):
		for j in range(m):
			d = i + j
			if matrix[i][j] == '1':
				nbs[d][1] += 1
			else:
				nbs[d][0] += 1
	res = 0
	middle = (max_length + 1) // 2
	for pos in range(middle):
		nb1 = nbs[pos]
		nb2 = nbs[max_length - pos]
		mini = min(nb1[0] + nb2[0], nb1[1] + nb2[1])
		res += mini
	print(res)


import os
import sys
from io import BytesIO, IOBase
import math
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')
for i in range(int(input())):
	(n, m) = map(int, input().split())
	mt = []
	raj = 'an'
	kri = 1
	mmm = list()
	mmm.append(-1)
	for _ in range(n):
		mt.append(list(map(int, input().split())))
	d = dict()
	step = [[0 for i in range(m)] for j in range(n)]
	step1 = [[0 for i in range(m)] for j in range(n)]
	d1 = dict()
	for i in range(n):
		for j in range(m):
			step[i][j] = i + j
			if i + j in d:
				d[i + j].append((i, j))
			else:
				d.update({i + j: [(i, j)]})
			step1[i][j] = n + m - 2 - i - j
			if n + m - 2 - i - j in d1:
				d1[n + m - 2 - i - j].append((i, j))
			else:
				d1.update({n + m - 2 - i - j: [(i, j)]})
	ans = 0
	for i in range((n + m - 1) // 2):
		cc = 0
		df = 0
		ccccc = cc + df
		if d[i] == d1[i]:
			continue
		for j in d[i]:
			df += mt[j[0]][j[1]]
			cc += 1
		for j in d1[i]:
			df += mt[j[0]][j[1]]
			cc += 1
		ans += min(cc - df, df)
	print(ans)


from collections import deque

def bfs(dep):
	global a, n, m, ans, d, check, cand
	while len(d):
		cand.append(list(d))
		l = len(d)
		for i in range(l):
			p = d.popleft()
			if p[1] < m - 1:
				if not check[p[0]][p[1] + 1]:
					d.append([p[0], p[1] + 1])
					check[p[0]][p[1] + 1] = True
			if p[0] < n - 1:
				if not check[p[0] + 1][p[1]]:
					d.append([p[0] + 1, p[1]])
					check[p[0] + 1][p[1]] = True
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	a = [list(map(int, input().split())) for i in range(n)]
	ans = 0
	d = deque([[0, 0]])
	check = [[False] * m for i in range(n)]
	check[0][0] = True
	cand = []
	bfs(0)
	for i in range((n + m - 1) // 2):
		x = [a[j[0]][j[1]] for j in cand[i] + cand[n + m - 1 - 1 - i]]
		ans += min(x.count(0), x.count(1))
	print(ans)


import sys
readline = sys.stdin.readline
read = sys.stdin.read
ns = lambda : readline().rstrip()
ni = lambda : int(readline().rstrip())
nm = lambda : map(int, readline().split())
nl = lambda : list(map(int, readline().split()))
prn = lambda x: print(*x, sep='\n')

def solve():
	(h, w) = nm()
	a = [nl() for _ in range(h)]
	d = dict()
	for i in range(h):
		for j in range(w):
			v = min(i + j, h + w - 2 - i - j)
			if v not in d:
				d[v] = [0, 0]
			d[v][a[i][j]] += 1
	ans = 0
	for x in d:
		if x * 2 != h + w - 2:
			ans += min(d[x])
	print(ans)
	return
T = ni()
for _ in range(T):
	solve()


tc = int(input().strip())
while tc:
	(n, m) = map(int, input().strip().split())
	inp = []
	for _ in range(n):
		inp.append(list(map(int, input().strip().split())))
	if m < n:
		grid = [[-1 for _ in range(n + 1)] for _ in range(m + 1)]
		for i in range(n):
			for j in range(m):
				grid[j + 1][i + 1] = inp[i][j]
		t = n
		n = m
		m = t
	else:
		grid = [[-1 for _ in range(m + 1)] for _ in range(n + 1)]
		for i in range(n):
			for j in range(m):
				grid[i + 1][j + 1] = inp[i][j]
	ans = 0
	lim = (n + m - 1) // 2
	for l in range(1, lim + 1):
		(nz, no) = (0, 0)
		i = 1
		j = l
		while i <= n and j >= 1:
			if grid[i][j] == 1:
				no += 1
			else:
				nz += 1
			i += 1
			j -= 1
		i = n
		j = m - l + 1
		while i >= 1 and j <= m:
			if grid[i][j] == 1:
				no += 1
			else:
				nz += 1
			i -= 1
			j += 1
		ans += min(nz, no)
	print(ans)
	tc -= 1


T = int(input())
for _ in range(T):
	(N, M) = map(int, input().split())
	A = [list(map(int, input().split())) for i in range(N)]
	L = N + M - 1
	c0 = [0] * L
	c1 = [0] * L
	for (i, row) in enumerate(A):
		for (j, a) in enumerate(row):
			if a == 0:
				c0[i + j] += 1
			else:
				c1[i + j] += 1
	M = L // 2
	ans = 0
	for i in range(M):
		a0 = c0[i] + c0[-1 - i]
		a1 = c1[i] + c1[-1 - i]
		ans += min(a0, a1)
	print(ans)


from collections import defaultdict

def test_case():
	(n, m) = map(int, input().split())
	a = [list(map(int, input().split())) for _ in range(n)]
	groups = defaultdict(lambda : defaultdict(int))
	for (y, row) in enumerate(a):
		for (x, val) in enumerate(row):
			groups[x + y][int(val)] += 1
	max_group = n + m - 2
	ans = 0
	if groups[0] != groups[max_group]:
		ans += 1
	for i in range(1, max_group // 2 + max_group % 2):
		zeros = groups[i][0] + groups[max_group - i][0]
		ones = groups[i][1] + groups[max_group - i][1]
		ans += min(ones, zeros)
	print(ans)
T = int(input())
for _ in range(T):
	test_case()


def getc(k, r, c):
	(ss, s) = (0, 0)
	global m
	for i in range(r):
		for j in range(c):
			if i + j == k or r + c - 2 - i - j == k:
				ss += 1
				s += m[i][j]
	return min(s, ss - s)
for _ in range(int(input())):
	(r, c) = map(int, input().split(' '))
	global m
	m = []
	for row in range(r):
		m.append(list(map(int, input().split(' '))))
	s = 0
	for i in range(0, (r + c - 1) // 2):
		s += getc(i, r, c)
	print(s)


def solve():
	(n, m) = map(int, input().split())
	grid = [list(map(int, input().split())) for _ in range(n)]
	counter = [[0, 0] for _ in range(n + m - 1)]
	for i in range(n):
		for j in range(m):
			counter[i + j][grid[i][j]] += 1
	ans = 0
	for p in range(n + m - 1):
		q = n + m - 2 - p
		if p >= q:
			continue
		c1 = counter[p][0] + counter[q][0]
		c2 = counter[p][1] + counter[q][1]
		ans += min(c1, c2)
	print(ans)
t = int(input())
while t > 0:
	t -= 1
	solve()


t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	g = [list(map(int, input().split())) for i in range(n)]
	a = [[] for i in range(n + m - 1)]
	if n < m:
		for i in range(n):
			for j in range(i + 1):
				a[i].append(g[i - j][j])
		for i in range(n, m):
			for j in range(n):
				a[i].append(g[j][i - j])
		for i in range(m, n + m - 1):
			for j in range(n - (i - m) - 1):
				a[i].append(g[j + (i - m + 1)][m - j - 1])
	elif n == m:
		for i in range(n):
			for j in range(i + 1):
				a[i].append(g[i - j][j])
		for i in range(m, n + m - 1):
			for j in range(n - (i - m) - 1):
				a[i].append(g[j + (i - m + 1)][m - j - 1])
	else:
		g2 = []
		for i in range(m):
			b = []
			for j in range(n):
				b.append(g[j][i])
			g2.append(b)
		(n, m) = (m, n)
		for i in range(n):
			for j in range(i + 1):
				a[i].append(g2[i - j][j])
		for i in range(n, m):
			for j in range(n):
				a[i].append(g2[j][i - j])
		for i in range(m, n + m - 1):
			for j in range(n - (i - m) - 1):
				a[i].append(g2[j + (i - m + 1)][m - j - 1])
	ans = 0
	for i in range(len(a) // 2):
		ans += min(a[i].count(0) + a[~i].count(0), a[i].count(1) + a[~i].count(1))
	print(ans)


for lo in range(int(input())):
	(n, m) = map(int, input().split())
	ls = []
	for i in range(n):
		a = [int(x) for x in input().split()]
		ls.append(a)
	x = (n + m) // 2
	res = [0 for i in range(x)]
	res1 = [0 for i in range(x)]
	for i in range(n):
		for j in range(m):
			y = i + j
			if ls[i][j] == 1:
				if y >= x:
					res[n + m - 2 - y] += 1
				else:
					res[y] += 1
			elif y >= x:
				res1[n + m - 2 - y] += 1
			else:
				res1[y] += 1
	if (n + m) % 2 == 0:
		x -= 1
	mn = 0
	for i in range(x):
		mn += min(res[i], res1[i])
	print(mn)


test = int(input())
while test > 0:
	test -= 1
	(m, n) = map(int, input().split())
	a = list()
	for _ in range(m):
		b = list(map(int, input().split()))
		a.append(b)
	dem = [0, 1]
	dem[0] = [0 for k in range(m + n + 2)]
	dem[1] = [0 for k in range(m + n + 2)]
	ans = int(0)
	for i in range(m):
		for j in range(n):
			x = i + j
			y = m - i - 1 + n - j - 1
			dem[a[i][j]][min(x, y)] += 1
	for x in range(0, (m + n - 1) // 2):
		ans += min(dem[0][x], dem[1][x])
	print(ans)


t = int(input())
for tc in range(t):
	chng = 0
	s = input().split()
	(n, m) = (int(s[0]), int(s[1]))
	num = []
	for i in range(n):
		s1 = list(map(int, input().split()))
		num.append(s1)
	if m >= n:
		if (m + n) % 2 == 0:
			x = 0
			ke = (m + n) // 2
			lis = [[] for i in range(ke)]
			co = 0
			l1 = 0
			for i1 in range(m + n - 1):
				y = i1 - x
				if co < ke and l1 == 0:
					x1 = x
					y1 = y
					while x1 >= 0 and y1 < m:
						lis[co].append(num[x1][y1])
						x1 -= 1
						y1 += 1
					x += 1
					if x >= n:
						x = n - 1
					co += 1
				else:
					if co == ke:
						co -= 1
					l1 = 1
					co -= 1
					x1 = x
					y1 = y
					while x1 >= 0 and y1 < m:
						lis[co].append(num[x1][y1])
						x1 -= 1
						y1 += 1
					x += 1
					if x >= n:
						x = n - 1
			for i in range(len(lis)):
				if i != len(lis) - 1:
					le = len(lis[i])
					ze = lis[i].count(0)
					if ze == 0 or ze == le:
						pass
					else:
						on = le - ze
						chng += min(ze, on)
			print(chng)
		else:
			x = 0
			lis = [[] for i in range((m + n) // 2)]
			ke = (m + n) // 2
			co = 0
			l1 = 0
			for i1 in range(m + n):
				y = i1 - x
				if co < ke and l1 == 0:
					x1 = x
					y1 = y
					while x1 >= 0 and y1 < m:
						lis[co].append(num[x1][y1])
						x1 -= 1
						y1 += 1
					x += 1
					if x >= n:
						x = n - 1
					co += 1
				else:
					l1 = 1
					co -= 1
					x1 = x
					y1 = y
					while x1 >= 0 and y1 < m:
						lis[co].append(num[x1][y1])
						x1 -= 1
						y1 += 1
					x += 1
					if x >= n:
						x = n - 1
			for i in lis:
				le = len(i)
				ze = i.count(0)
				if ze == 0 or ze == le:
					pass
				else:
					on = le - ze
					chng += min(ze, on)
			print(chng)
	else:
		numd = [[] for i in range(m)]
		for i in range(n):
			for j in range(m):
				numd[j].append(num[i][j])
		(m, n) = (n, m)
		if (m + n) % 2 == 0:
			x = 0
			ke = (m + n) // 2
			lis = [[] for i in range(ke)]
			co = 0
			l1 = 0
			for i1 in range(m + n - 1):
				y = i1 - x
				if co < ke and l1 == 0:
					x1 = x
					y1 = y
					while x1 >= 0 and y1 < m:
						lis[co].append(numd[x1][y1])
						x1 -= 1
						y1 += 1
					x += 1
					if x >= n:
						x = n - 1
					co += 1
				else:
					if co == ke:
						co -= 1
					l1 = 1
					co -= 1
					x1 = x
					y1 = y
					while x1 >= 0 and y1 < m:
						lis[co].append(numd[x1][y1])
						x1 -= 1
						y1 += 1
					x += 1
					if x >= n:
						x = n - 1
			for i in range(len(lis)):
				if i != len(lis) - 1:
					le = len(lis[i])
					ze = lis[i].count(0)
					if ze == 0 or ze == le:
						pass
					else:
						on = le - ze
						chng += min(ze, on)
			print(chng)
		else:
			x = 0
			lis = [[] for i in range((m + n) // 2)]
			ke = (m + n) // 2
			co = 0
			l1 = 0
			for i1 in range(m + n):
				y = i1 - x
				if co < ke and l1 == 0:
					x1 = x
					y1 = y
					while x1 >= 0 and y1 < m:
						lis[co].append(numd[x1][y1])
						x1 -= 1
						y1 += 1
					x += 1
					if x >= n:
						x = n - 1
					co += 1
				else:
					l1 = 1
					co -= 1
					x1 = x
					y1 = y
					while x1 >= 0 and y1 < m:
						lis[co].append(numd[x1][y1])
						x1 -= 1
						y1 += 1
					x += 1
					if x >= n:
						x = n - 1
			for i in lis:
				le = len(i)
				ze = i.count(0)
				if ze == 0 or ze == le:
					pass
				else:
					on = le - ze
					chng += min(ze, on)
			print(chng)


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	a = []
	for _ in range(n):
		b = list(map(int, input().split()))
		a.append(b)
	x = n + m - 1
	y = []
	for _ in range(x):
		y.append([])
	total = 0
	for i in range(n):
		for j in range(m):
			y[i + j].append(a[i][j])
	for k in range(x // 2):
		z = y[k] + y[-1 - k]
		total += min(z.count(0), z.count(1))
	print(total)


import sys
input = sys.stdin.readline
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	one = [0] * (n + m - 1)
	zero = [0] * (n + m - 1)
	for i in range(n):
		a = list(map(int, input().split()))
		for j in range(m):
			one[i + j] += a[j] == 1
			zero[i + j] += a[j] == 0
	res = 0
	for i in range((n + m - 1) // 2):
		s = one[i] + one[n + m - 2 - i]
		t = zero[i] + zero[n + m - 2 - i]
		res += min(s, t)
	print(res)


def main():
	import sys
	input = sys.stdin.buffer.readline
	sys.setrecursionlimit(10 ** 5)
	t = int(input())
	for _ in range(t):
		(n, m) = map(int, input().split())
		A = [list(map(int, input().split())) for i in range(n)]
		D = [[0] * m for i in range(n)]
		for i in range(n):
			for j in range(m):
				if i == 0:
					if j > 0:
						D[i][j] = D[i][j - 1] + 1
				elif j == 0:
					D[i][j] = D[i - 1][j] + 1
				else:
					D[i][j] = min(D[i - 1][j], D[i][j - 1]) + 1
		import collections
		d = collections.defaultdict(list)
		for i in range(n):
			for j in range(m):
				d[min(D[i][j], n + m - 2 - D[i][j])].append(A[i][j])
		ans = 0
		for i in range((n + m - 1) // 2):
			C = collections.Counter(d[i]).most_common()
			if len(C) == 2:
				ans += C[1][1]
		print(ans)
main()


t = int(input())
for q in range(t):
	(n, m) = map(int, input().split())
	matr = []
	for i in range(n):
		matr.append(list(map(int, input().split())))
	s = {}
	for i in range(n):
		for j in range(m):
			s[i + j] = s.get(i + j, 0) + matr[i][j]
	ans = 0
	x = 0
	y = n + m - 2
	while x < y:
		ma = min(min(n, m), x + 1)
		ans += min(ma - s[x] + ma - s[y], s[x] + s[y])
		x += 1
		y -= 1
	print(ans)


import sys
import math as mt
input = sys.stdin.buffer.readline
t = int(input())
for __ in range(t):
	(n, m) = map(int, input().split())
	d = {}
	d1 = {}
	for i in range(n + m + 1):
		d[i] = []
		d1[i] = []
	l = []
	for i in range(n):
		l.append(list(map(int, input().split())))
	for i in range(n):
		for j in range(m):
			d[i + j].append(l[i][j])
	for i in range(n + m):
		(z, o) = (0, 0)
		for j in range(len(d[i])):
			if d[i][j] == 0:
				z += 1
			else:
				o += 1
		d1[i].append(z)
		d1[i].append(o)
	(i, j) = (0, n + m - 2)
	ans = 0
	while i < j:
		ans += min(d1[i][0] + d1[j][0], d1[i][1] + d1[j][1])
		i += 1
		j -= 1
	print(ans)


import sys
input = sys.stdin.readline
I = lambda : list(map(int, input().split()))
(t,) = I()
for _ in range(t):
	(n, m) = I()
	mt = []
	an = 0
	for _ in range(n):
		mt.append(I())
	d = {}
	for i in range(n):
		for j in range(m):
			l = d.get(i + j, [0, 0])
			if mt[i][j]:
				l[1] += 1
			else:
				l[0] += 1
			d[i + j] = list(l)
	for i in range((n + m - 1) // 2):
		x = d[i]
		y = d[n + m - 2 - i]
		an += min(x[0] + y[0], x[1] + y[1])
	print(an)


import sys
input = sys.stdin.readline
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	A = [list(map(int, input().split())) for _ in range(n)]
	plen = n + m - 1
	V = [[False] * m for _ in range(n)]
	V[0][0] = V[-1][-1] = True
	cost = 0
	Q = [(0, 0), (m - 1, n - 1)]
	for _ in range(plen // 2):
		NQ = []
		tot = len(Q)
		zero = sum((A[y][x] == 0 for (x, y) in Q))
		one = tot - zero
		cost += min(zero, one)
		for (x, y) in Q:
			for (dx, dy) in ((-1, 0), (1, 0), (0, -1), (0, 1)):
				nx = x + dx
				ny = y + dy
				if 0 <= nx < m and 0 <= ny < n:
					if V[ny][nx]:
						continue
					V[ny][nx] = True
					NQ.append((nx, ny))
		Q = NQ
	print(cost)


import os, 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')
from math import ceil
mod = 10 ** 9 + 7
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	matrix = [0 for _ in range(n)]
	for i in range(n):
		l = list(map(int, input().split()))
		matrix[i] = l
	frequency_count_ones_zeroes = [[0, 0] for _ in range(n + m - 1)]
	for i in range(n):
		for j in range(m):
			at = i + j
			frequency_count_ones_zeroes[at][matrix[i][j]] += 1
	minimum_conversions = 0
	for i in range(n + m - 1):
		corresponding_j = n + m - 2 - i
		if i <= corresponding_j:
			continue
		minimum_conversions += min(frequency_count_ones_zeroes[i][0] + frequency_count_ones_zeroes[corresponding_j][0], frequency_count_ones_zeroes[i][1] + frequency_count_ones_zeroes[corresponding_j][1])
	print(minimum_conversions)


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	a = [list(map(int, input().split())) for i in range(n)]
	temp = []
	lol = (n + m) // 2
	for i in range(1, m + 1):
		k = i
		j = 1
		temp.append([0, 0])
		while k and j <= n:
			temp[i - 1][0] += 1
			temp[i - 1][1] += a[j - 1][k - 1]
			k -= 1
			j += 1
	for i in range(2, n + 1):
		k = i
		j = m
		temp.append([0, 0])
		while j > 0 and k <= n:
			temp[m + i - 2][0] += 1
			temp[m + i - 2][1] += a[k - 1][j - 1]
			j -= 1
			k += 1
	ans = 0
	j = n + m
	for i in range(lol - 1):
		sai = temp[i][0] + temp[j - 2][0]
		cha = temp[i][1] + temp[j - 2][1]
		ans += min(sai - cha, cha)
		j -= 1
	if (n + m) % 2 == 0:
		pass
	else:
		sai = temp[lol][0] + temp[lol - 1][0]
		cha = temp[lol][1] + temp[lol - 1][1]
		ans += min(sai - cha, cha)
	print(ans)


import sys
input = sys.stdin.readline
import heapq
import copy
import math
import decimal

class Node:

	def _init_(self, val):
		self.data = val
		self.left = None
		self.right = None

def pre_sum(arr):
	p = [0]
	for i in arr:
		p.append(p[-1] + i)
	p.pop(0)
	return p

def pre_back(arr):
	p = [0]
	for i in arr:
		p.append(p[-1] + i)
	p.pop(0)
	return p

def bin_search(arr, l, r, val):
	if arr[r] <= val:
		return r + 1
	if r - l < 2:
		if arr[l] > val:
			return l
		else:
			return r
	mid = int((l + r) / 2)
	if arr[mid] <= val:
		return bin_search(arr, mid, r, val)
	else:
		return bin_search(arr, l, mid, val)

def search_leftmost(arr, val):

	def helper(arr, l, r, val):
		print(l, r)
		if arr[l] == val:
			return l
		if r - l <= 1:
			if arr[r] == val:
				return r
			else:
				print('not found')
				return
		mid = int((r + l) / 2)
		if arr[mid] >= val:
			return helper(arr, l, mid, val)
		else:
			return helper(arr, mid, r, val)
	return helper(arr, 0, len(arr) - 1, val)

def search_rightmost(arr, val):

	def helper(arr, l, r, val):
		print(l, r)
		if arr[r] == val:
			return r
		if r - l <= 1:
			if arr[l] == val:
				return r
			else:
				print('not found')
				return
		mid = int((r + l) / 2)
		if arr[mid] > val:
			return helper(arr, l, mid, val)
		else:
			return helper(arr, mid, r, val)
	return helper(arr, 0, len(arr) - 1, val)

def preorder_postorder(root, paths, parent, left, level):
	l = 0
	queue = [root]
	while queue != []:
		node = queue[-1]
		flag = 0
		for i in paths[node]:
			if i != parent[node] and level[i] == sys.maxsize:
				parent[i] = node
				level[i] = level[node] + 1
				flag = 1
				queue.append(i)
		if flag == 0:
			left[parent[node]] += 1 + left[node]
			queue.pop()
	return [parent, left, level]

def nCr(n, r, p):
	if r == 0:
		return 1
	num = den = 1
	for i in range(r):
		num = num * (n - i) % p
		den = den * (i + 1) % p
	return num * pow(den, p - 2, p) % p

def f_exp(p, k0, k1, l):
	ans = 1
	k = k0 - k1
	while k != 0:
		if k % 2 == 0:
			k = k // 2
			p = p * p
		else:
			ans = ans * p
			k = (k - 1) // 2
			p = p * p
		if ans > l:
			ans = -1
			break
	return ans

def inp():
	return int(input())

def inlt():
	return list(map(int, input().split()))

def insr():
	s = input()
	return list(s[:len(s) - 1])

def insr2():
	s = input()
	return s[:len(s) - 1]

def invr():
	return map(int, input().split())

def pr_list(a):
	print(*a, sep=' ')

def main():
	tests = inp()
	mod = 1000000007
	limit = 10 ** 18
	ans = 0
	for test in range(tests):
		[n, m] = inlt()
		mat = []
		for i in range(n):
			mat.append(inlt())
		ans = 0
		steps = (n + m - 1) // 2
		for i in range(0, steps):
			ones = 0
			t = 0
			for j in range(0, i + 1):
				if j < n and i - j < m:
					ones = ones + mat[j][i - j]
					t = t + 1
				if n - 1 - j >= 0 and m - 1 - (i - j) >= 0:
					ones = ones + mat[n - 1 - j][m - 1 - (i - j)]
					t = t + 1
			ans = ans + min(ones, t - ones)
		print(ans)
main()


t = int(input())
for _ in range(t):
	(n, m) = list(map(int, input().split()))
	l = []
	for _ in range(n):
		l.append(list(map(int, input().split())))
	zeroes = [0] * (m + n - 1)
	ones = [0] * (m + n - 1)
	for i in range(n):
		for j in range(m):
			if l[i][j] == 0:
				zeroes[i + j] += 1
			else:
				ones[i + j] += 1
	out = 0
	for i in range((m + n - 1) // 2):
		z = zeroes[i] + zeroes[m + n - 2 - i]
		o = ones[i] + ones[m + n - 2 - i]
		out += min(o, z)
	print(out)


testy = int(input())
results = []
for k in range(testy):
	(n, m) = map(int, input().split())
	plansza = []
	przek = []
	for i in range(n + m - 1):
		przek.append([0, 0])
	zmiany = 0
	for i in range(n):
		plansza.append(list(map(int, input().split())))
	for i in range(n):
		for j in range(m):
			przek[i + j][plansza[i][j]] += 1
	for i in range(len(przek) // 2):
		zmiany = zmiany + min(przek[i][0] + przek[len(przek) - 1 - i][0], przek[i][1] + przek[len(przek) - 1 - i][1])
	results.append(zmiany)
for result in results:
	print(result)


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	zeroes = [0 for i in range(n + m - 1)]
	ones = [0 for i in range(n + m - 1)]
	arr = []
	ans = 0
	for i in range(n):
		a = list(map(int, input().split()))
		arr.append(a)
	for i in range(n):
		for j in range(m):
			if arr[i][j] == 1:
				ones[i + j] += 1
			else:
				zeroes[i + j] += 1
	v = (m - 1 + n - 1) // 2
	for i in range(v + 1):
		if i != v or (m + n) % 2 != 0:
			x = ones[i] + ones[n + m - i - 2]
			y = zeroes[i] + zeroes[n + m - 2 - i]
			ans += min(x, y)
	print(ans)


t = int(input())
for i in range(t):
	(n, m) = list(map(int, input().rstrip().split()))
	mat = []
	for _ in range(n):
		mat.append(list(map(int, input().rstrip().split())))
	(i, j) = (0, max(n - 1, m - 1))
	res = 0
	flag = 0 if j == n - 1 else 1
	while True:
		(ones, zeros) = (0, 0)
		row = 0 if flag == 1 else j
		col = i if flag == 1 else m - 1
		while 0 <= row < n and 0 <= col < m:
			if mat[row][col] == 2:
				flag = 2
				break
			ones += 1 if mat[row][col] == 1 else 0
			zeros += 1 if mat[row][col] == 0 else 0
			mat[row][col] = 2
			col -= 1
			row += 1
		row = n - 1 if flag == 1 else i
		col = j if flag == 1 else 0
		while 0 <= row < n and 0 <= col < m:
			if mat[row][col] == 2:
				flag = 2
				break
			ones += 1 if mat[row][col] == 1 else 0
			zeros += 1 if mat[row][col] == 0 else 0
			mat[row][col] = 2
			col += 1
			row -= 1
		if flag == 2:
			break
		res += min(ones, zeros)
		i += 1
		j -= 1
	print(res)


import sys
from math import *
from collections import defaultdict
from queue import deque
from heapq import heappush, heappop
lines = [line.strip() for line in sys.stdin.readlines()]
T = int(lines[0])
cur = 1
for t in range(T):
	(n, m) = map(int, lines[cur].split())
	A = [list(map(int, line.split())) for line in lines[cur + 1:cur + 1 + n]]
	cur += 1 + n
	ret = 0
	for s in range((n + m - 3) // 2 + 1):
		t = n + m - 2 - s
		(a, b) = (0, 0)
		for i in range(n):
			for j in [s - i, t - i]:
				if 0 <= j < m:
					if A[i][j] == 0:
						a += 1
					else:
						b += 1
		ret += min(a, b)
	print(ret)


import math
for t in range(int(input())):
	(n, m) = map(lambda x: int(x), input().split(' '))
	arr = []
	for i in range(n):
		arr.append(list(map(lambda x: int(x), input().split(' '))))
	c = 0
	if m % 2 == n % 2:
		ml = (m + n) / 2 - 1
	else:
		ml = math.floor((m + n) / 2)
	for i in range(int(ml)):
		on = 0
		tw = 0
		for j in range(i + 1):
			if j >= n or i - j >= m:
				continue
			if arr[j][i - j]:
				on += 1
			else:
				tw += 1
			if arr[n - j - 1][m - 1 - (i - j)]:
				on += 1
			else:
				tw += 1
		if on > tw:
			c += tw
		else:
			c += on
	print(c)


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 *
from copy import *
from collections import deque
from collections import Counter as counter
from itertools import combinations as comb
from itertools import permutations as permutate
from bisect import bisect_left as bl
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
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 zerolist(n):
	return [0] * n

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

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

def printlist(a):
	for p in range(0, len(a)):
		out(str(a[p]) + ' ')

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
from operator import add

def solve():
	(n, m) = sep()
	ar = []
	for _ in range(n):
		ar.append(lis())
	k = (n - 1 + m - 1) // 2
	from collections import defaultdict

	def g():
		return [0, 0]
	d = defaultdict(g)
	for i in range(n):
		for j in range(m):
			if ar[i][j] == 1:
				t = min(i + j, n - 1 - i + m - 1 - j)
				d[t][1] += 1
			else:
				t = min(i + j, n - 1 - i + m - 1 - j)
				d[t][0] += 1
	ans = 0
	for i in d.keys():
		if (n + m - 1) % 2 == 1 and i == (n + m - 1) // 2:
			continue
		t = min(d[i])
		ans += t
	print(ans)
testcase(int(inp()))


import sys
import math
import collections

def set_debug(debug_mode=False):
	if debug_mode:
		fin = open('input.txt', 'r')
		sys.stdin = fin

def int_split_input():
	return list(map(int, input().split()))
t = int(input())
for ti in range(1, t + 1):
	(n, m) = int_split_input()
	A = []
	res = 0
	for _ in range(n):
		A.append(int_split_input())
	l = 0
	r = m - 1 + n - 1
	while l < r:
		d = {0: 0, 1: 0}
		for row in range(0, n):
			col_l = l - row
			col_r = r - row
			if 0 <= col_l < m:
				d[A[row][col_l]] += 1
			if 0 <= col_r < m:
				d[A[row][col_r]] += 1
		res += min(d[0], d[1])
		l += 1
		r -= 1
	print(res)


for _ in range(int(input())):
	(n, m) = list(map(int, input().split()))
	test = []
	for i in range(n):
		test.append(list(map(int, input().split())))
	max_col = len(test[0])
	max_row = len(test)
	fdiag = [[] for _ in range(max_row + max_col - 1)]
	min_bdiag = -max_row + 1
	for x in range(max_col):
		for y in range(max_row):
			fdiag[x + y].append(test[y][x])
	n = len(fdiag)
	count = 0
	for i in range(n // 2):
		first = fdiag[i]
		second = fdiag[n - i - 1]
		a = len(second) * 2 - (first.count(1) + second.count(1))
		b = first.count(1) + second.count(1)
		count += min(a, b)
	print(count)


import sys
input = lambda : sys.stdin.readline().strip('\r\n')
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	a = [list(map(int, input().split())) for i in range(n)]
	l = n + m - 1
	mat = [[] for i in range(l)]
	ans = 0
	for i in range(n):
		for j in range(m):
			mat[i + j].append(a[i][j])
	for i in range(l // 2):
		alpha = mat[i] + mat[-1 - i]
		ans += min(alpha.count(1), alpha.count(0))
	print(ans)


T = int(input())
for _ in range(T):
	(n, m) = [int(i) for i in input().split()]
	A = [[int(i) for i in input().split()] for j in range(n)]
	my_dict = dict()
	for i in range((n + m) // 2):
		my_dict[i] = [0, 0]
	for i in range(n):
		for j in range(m):
			key = min([i + j, n - 1 - i + m - 1 - j])
			my_dict[key][A[i][j]] += 1
	ans = 0
	for i in range((n + m - 1) // 2):
		ans += min(my_dict[i])
	print(ans)


for _ in range(int(input())):
	ans = 0
	(n, m) = map(int, input().split())
	l = [list(map(int, input().split())) for __ in range(n)]
	cnt = [[0, 0] for __ in range(n + m - 1)]
	for i in range(n):
		for j in range(m):
			cnt[i + j][l[i][j]] += 1
	for i in range(n + m - 1):
		j = n + m - 2 - i
		if i <= j:
			continue
		ans += min(cnt[i][0] + cnt[j][0], cnt[i][1] + cnt[j][1])
	print(ans)


import math, string, itertools, fractions, heapq, collections, re, array, bisect, sys, copy, functools
inf = 10 ** 20
eps = 1.0 / 10 ** 10
mod = 10 ** 9 + 7
mod2 = 998244353
dd = [(-1, 0), (0, 1), (1, 0), (0, -1)]
ddn = [(-1, 0), (-1, 1), (0, 1), (1, 1), (1, 0), (1, -1), (0, -1), (-1, -1)]

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

def LLI():
	return [list(map(int, l.split())) for l in sys.stdin.readlines()]

def LI_():
	return [int(x) - 1 for x in sys.stdin.readline().split()]

def LF():
	return [float(x) for x in sys.stdin.readline().split()]

def LS():
	return sys.stdin.readline().split()

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

def F():
	return float(sys.stdin.readline())

def S():
	return input()

def pf(s):
	return print(s, flush=True)

def pe(s):
	return print(str(s), file=sys.stderr)

def JA(a, sep):
	return sep.join(map(str, a))

def JAA(a, s, t):
	return s.join((t.join(map(str, b)) for b in a))

def IF(c, t, f):
	return t if c else f

def YES(c):
	return IF(c, 'YES', 'NO')

def Yes(c):
	return IF(c, 'Yes', 'No')

def main():
	t = I()
	rr = []
	for _ in range(t):
		(n, m) = LI()
		aa = [LI() for _ in range(n)]
		v = set()
		v.add((0, 0))
		c = collections.defaultdict(lambda : collections.defaultdict(int))
		q = [(0, 0, 0)]
		qi = 0
		while qi < len(q):
			(i, j, k) = q[qi]
			qi += 1
			c[k][aa[i][j]] += 1
			nk = k + 1
			for (di, dj) in dd:
				ni = i + di
				nj = j + dj
				if ni < 0 or ni >= n or nj < 0 or (nj >= m):
					continue
				if (ni, nj) in v:
					continue
				v.add((ni, nj))
				q.append((ni, nj, nk))
		r = 0
		for k in range((n + m - 1) // 2):
			bk = n + m - 1 - k - 1
			c[k][0] += c[bk][0]
			c[k][1] += c[bk][1]
			r += min(c[k].values())
		rr.append(r)
	return JA(rr, '\n')
print(main())


def f():
	(n, m) = [int(s) for s in input().split()]
	M = []
	for _ in range(n):
		M.append([int(s) for s in input().split()])
	if n > m:
		M2 = [[0] * n for _ in range(m)]
		for i in range(n):
			for j in range(m):
				M2[j][i] = M[i][j]
		M = M2
		(n, m) = (m, n)

	def count(s):
		end = min(n, s + 1)
		all = end * 2
		ones = 0
		for i in range(end):
			j = s - i
			ones += M[i][j]
			ones += M[n - 1 - i][m - 1 - j]
		return min(all - ones, ones)
	ans = 0
	half = (n + m - 2) * 0.5
	s = 0
	while s < half:
		ans += count(s)
		s += 1
	print(ans)
for t in range(int(input())):
	f()


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	l = []
	for i in range(n):
		l.append(list(map(int, input().split())))
	a1 = [0] * (m + n - 1)
	a2 = [0] * (m + n - 1)
	for i in range(n):
		for j in range(m):
			a2[i + j] += 1
	for i in range(n):
		for j in range(m):
			a1[i + j] += l[i][j]
	ans = 0
	vi = n + m - 1
	for i in range(vi // 2):
		t = a1[i] + a1[vi - i - 1]
		ans += min(t, 2 * a2[i] - t)
	print(ans)


t = int(input())
for _ in range(t):
	(row, col) = (int(var) for var in input().split())
	mat = []
	for _ in range(row):
		mat.append([int(var) for var in input().split()])
	diagonals = []
	for y in range(col):
		x = 0
		(zeros, ones) = (0, 0)
		while x < row and y >= 0:
			zeros += not mat[x][y]
			ones += mat[x][y]
			x += 1
			y -= 1
		diagonals.append([zeros, ones])
	for x in range(1, row):
		(zeros, ones) = (0, 0)
		y = col - 1
		while y >= 0 and x < row:
			zeros += not mat[x][y]
			ones += mat[x][y]
			x += 1
			y -= 1
		diagonals.append([zeros, ones])
	ans = 0
	length = len(diagonals) - 1
	for i in range(len(diagonals)):
		if i < length - i:
			ans += min(diagonals[i][0] + diagonals[length - i][0], diagonals[i][1] + diagonals[length - i][1])
		else:
			break
	print(ans)


I = lambda : map(int, input().split())
(t,) = I()
for _ in [0] * t:
	(n, m) = I()
	a = 0
	g = {}
	for i in range(n):
		s = [*I()]
		for j in range(m):
			if not g.get(i + j):
				g[i + j] = [0, 0]
			g[i + j][s[j]] += 1
	k = n + m - 1
	for i in range(k):
		if i != k - i - 1:
			a += min(g[i][0] + g[k - i - 1][0], g[i][1] + g[k - i - 1][1])
	print(a // 2)


for t in range(int(input())):
	(n, m) = map(int, input().split())
	mat = []
	count = 0
	for i in range(n):
		mat.append(list(map(int, input().split())))
	if (n + m) % 2 == 0:
		x = (n + m) // 2 - 1
	else:
		x = (n + m) // 2
	for i in range(x):
		ones = 0
		zeroes = 0
		for j in range(min(i + 1, m, n)):
			if i > n - 1:
				if mat[n - 1 - j][i + j - n + 1] == 1:
					ones += 1
				else:
					zeroes += 1
				if mat[-n + j][-1 - i + n - 1 - j] == 1:
					ones += 1
				else:
					zeroes += 1
			else:
				if mat[i - j][j] == 1:
					ones += 1
				else:
					zeroes += 1
				if mat[-1 - i + j][-1 - j] == 1:
					ones += 1
				else:
					zeroes += 1
		if zeroes > ones:
			count += ones
		else:
			count += zeroes
	print(count)


def f():
	return list(map(int, input().split()))
for _ in range(int(input())):
	(a, b) = f()
	s = []
	for _ in range(a):
		s.append(f())
	p = [(0, 0)]
	q = [(a - 1, b - 1)]
	ans = int(s[0][0] != s[a - 1][b - 1])
	for _ in range(4, a + b, 2):

		def g(arr, neg):
			tmp = set()
			for (i, j) in [(neg, 0), (0, neg)]:
				for (c, d) in arr:
					c += i
					d += j
					if 0 <= c < a and 0 <= d < b:
						tmp.add((c, d))
			SUM = 0
			for (c, d) in tmp:
				SUM += s[c][d]
			return (tmp, SUM)
		(tp, sp) = g(p, 1)
		(tq, sq) = g(q, -1)
		SUM = sp + sq
		ans += min(SUM, len(tp) + len(tq) - SUM)
		p = tp
		q = tq
	print(ans)


q = int(input())
for T in range(q):
	(n, m) = map(int, input().split())
	a = []
	for i in range(n):
		a.append(list(map(int, input().split())))
	bd = (n + m) // 2
	dig = []
	for i in range(bd):
		dig.append([])
	x = bd - 1
	if (n + m) % 2 == 0:
		x = x - 1
	for i in range(n):
		for j in range(m):
			if i + j >= bd:
				dig[x - (i + j - bd)].append(a[i][j])
			else:
				dig[i + j].append(a[i][j])
	res = 0
	if (n + m) % 2 == 0:
		bd = bd - 1
	for i in range(bd):
		c1 = 0
		sz = len(dig[i])
		for j in range(sz):
			c1 = c1 + dig[i][j]
		if c1 < sz - c1:
			res = res + c1
		else:
			res = res + sz - c1
	print(res)


from collections import deque
import sys

def inp():
	return sys.stdin.readline().strip()
for _ in range(int(inp())):
	(n, m) = map(int, inp().split())
	a = []
	ct = 0
	for i in range(n):
		ll = list(map(int, inp().split()))
		a.append(ll)
	p = n + m - 2
	d = {}
	done = set()
	for i in range(n):
		for j in range(m):
			if (i + j) * 2 == p:
				continue
			tp = min(i + j, p - (i + j))
			if tp not in d:
				d[tp] = [0, 0]
			d[tp][a[i][j]] += 1
	for i in d:
		ct += min(d[i])
	print(ct)


t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	arr = []
	for i in range(n):
		arr += [[int(j) for j in input().split()]]
	count = [[] for i in range(n + m - 1)]
	for i in range(n):
		for j in range(m):
			count[i + j] += [arr[i][j]]
	ans = 0
	for i in range(len(count) // 2):
		one = 0
		zero = 0
		for j in count[i]:
			if j == 1:
				one += 1
			else:
				zero += 1
		for j in count[len(count) - 1 - i]:
			if j == 1:
				one += 1
			else:
				zero += 1
		ans += min(one, zero)
	print(ans)


from collections import Counter
for testcase in range(int(input())):
	(n, m) = map(int, input().split())
	grid = [list(map(int, input().split())) for i in range(n)]
	eq = [[] for i in range(n + m)]
	for nn in range(n):
		for mm in range(m):
			eq[min(nn + mm, n - 1 - nn + (m - 1 - mm))].append(grid[nn][mm])
	if (n + m) % 2 == 0:
		eq.pop((n + m - 2) // 2)
	eq = [i for i in eq if eq]
	ans = 0
	for i in eq:
		c = Counter(i)
		ans += len(i) - max(c[0], c[1])
	print(ans)


from sys import stdin, exit
input = stdin.readline

def i():
	return input()

def ii():
	return int(input())

def iis():
	return map(int, input().split())

def liis():
	return list(map(int, input().split()))

def print_array(a):
	print(' '.join(map(str, a)))
t = ii()
for _ in range(t):
	(n, m) = iis()
	matrix = []
	for i in range(n):
		a = liis()
		matrix.append(a)
	if n > m:
		new_matrix = []
		for i in range(m):
			new_matrix.append([])
			for j in range(n):
				new_matrix[i].append(matrix[j][i])
		matrix = new_matrix
		(n, m) = (m, n)
	count = 0
	for i in range(m):
		zerosF = onesF = zerosS = onesS = 0
		jose = False
		passaram = set()
		if i > m - i - 1 + n - 1:
			break
		for j in range(min(i + 1, n)):
			passaram.add((j, i - j))
			if matrix[j][i - j] == 0:
				zerosF += 1
			else:
				onesF += 1
		for j in range(min(i + 1, n)):
			if (n - j - 1, m - i + j - 1) in passaram:
				jose = True
			if matrix[n - j - 1][m - i + j - 1] == 0:
				zerosS += 1
			else:
				onesS += 1
		if jose:
			break
		count += min(zerosS + zerosF, onesS + onesF)
	print(count)


n = int(input())
for _ in range(n):
	(r, c) = map(int, input().split())
	grid = []
	d = {}
	for i in range(r):
		l = list(map(int, input().split()))
		grid.append(l)
	for i in range(r):
		for j in range(c):
			s = i + j
			s1 = r - i - 1 + c - j - 1
			if s != s1 and s1 not in d:
				t = grid[i][j]
				t1 = grid[r - i - 1][c - j - 1]
				if s not in d:
					d[s] = [0, 0]
				d[s][t] += 1
				d[s][t1] += 1
	c = 0
	for i in d:
		c += min(d[i])
	print(c)


from sys import stdin, stdout
import math, queue, heapq
fastinput = stdin.readline
fastout = stdout.write
t = int(fastinput())
while t:
	t -= 1
	(n, m) = map(int, fastinput().split())
	y = n + m - 1
	count1 = [0] * y
	for j in range(n):
		k = 0
		for i in fastinput().split():
			if int(i) == 0:
				k += 1
				continue
			else:
				count1[j + k] += 1
				k += 1
	change = 0
	m = min(n, m)
	for i in range(y // 2):
		x = min(2 * (i + 1), 2 * m)
		change += min(count1[i] + count1[y - i - 1], x - count1[i] - count1[y - i - 1])
	print(change)


def solve():
	(n, m) = map(int, input().split(' '))
	matrix = []
	for _ in range(n):
		row = list(map(int, input().split(' ')))
		matrix.append(row)
	level = 0
	max_level = m + n - 2
	ans = 0
	while level < max_level:
		number0 = 0
		number1 = 0
		for i in range(level + 1):
			if i >= n or level - i >= m or level - i < 0:
				continue
			if matrix[i][level - i]:
				number1 += 1
			else:
				number0 += 1
		for i in range(level + 1):
			_i = n - 1 - i
			if _i < 0 or max_level - _i >= m or max_level - _i < 0:
				continue
			if matrix[_i][max_level - _i]:
				number1 += 1
			else:
				number0 += 1
		level += 1
		max_level -= 1
		ans += min(number0, number1)
	return ans
T = int(input())
ans = []
for _ in range(T):
	ans.append(solve())
for a in ans:
	print(a)


import sys
input = sys.stdin.readline
from math import ceil, floor, factorial

def swaparr(arr, a, b):
	temp = arr[a]
	arr[a] = arr[b]
	arr[b] = temp

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

def nCr(n, k):
	if k > n - k:
		k = n - k
	res = 1
	for i in range(k):
		res = res * (n - i)
		res = res / (i + 1)
	return int(res)

def upper_bound(a, x, lo=0):
	hi = len(a)
	while lo < hi:
		mid = (lo + hi) // 2
		if a[mid] < x:
			lo = mid + 1
		else:
			hi = mid
	return lo

def primefs(n):
	primes = {}
	while n % 2 == 0:
		primes[2] = primes.get(2, 0) + 1
		n = n // 2
	for i in range(3, int(n ** 0.5) + 2, 2):
		while n % i == 0:
			primes[i] = primes.get(i, 0) + 1
			n = n // i
	if n > 2:
		primes[n] = primes.get(n, 0) + 1
	return primes

def power(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

def swap(a, b):
	temp = a
	a = b
	b = temp
	return (a, b)

def find(x, link):
	p = x
	while p != link[p]:
		p = link[p]
	while x != p:
		nex = link[x]
		link[x] = p
		x = nex
	return p

def union(x, y, link, size):
	x = find(x, link)
	y = find(y, link)
	if size[x] < size[y]:
		(x, y) = swap(x, y)
	if x != y:
		size[x] += size[y]
		link[y] = x

def sieve(n):
	prime = [True for i in range(n + 1)]
	p = 2
	while p * p <= n:
		if prime[p] == True:
			for i in range(p * p, n + 1, p):
				prime[i] = False
		p += 1
	return prime
MAXN = int(1000000.0 + 5)

def spf_sieve():
	spf[1] = 1
	for i in range(2, MAXN):
		spf[i] = i
	for i in range(4, MAXN, 2):
		spf[i] = 2
	for i in range(3, ceil(MAXN ** 0.5), 2):
		if spf[i] == i:
			for j in range(i * i, MAXN, i):
				if spf[j] == j:
					spf[j] = i

def factoriazation(x):
	ret = {}
	while x != 1:
		ret[spf[x]] = ret.get(spf[x], 0) + 1
		x = x // spf[x]
	return ret

def int_array():
	return list(map(int, input().strip().split()))

def str_array():
	return input().strip().split()
MOD = int(1000000000.0) + 7
CMOD = 998244353
INF = float('inf')
NINF = -float('inf')
for _ in range(int(input())):
	(n, m) = int_array()
	a = []
	for __ in range(n):
		a.append(int_array())
	ans = 0
	dick = {}
	for i in range(n):
		for j in range(m):
			(x, y) = (i + j, m + n - i - j - 2)
			k = min(x, y)
			if x == y:
				continue
			if k in dick:
				dick[k].append(a[i][j])
			else:
				dick[k] = [a[i][j]]
	for i in dick:
		x = len(dick[i])
		y = dick[i].count(1)
		ans += min(y, x - y)
	print(ans)


T = int(input())
for t_itr in range(T):
	(N, M) = map(int, input().rstrip().split())
	A = []
	for _ in range(N):
		A.append(list(map(int, input().rstrip().split())))
	result = 0
	C = [0 for j in range(N + M - 1)]
	T = [0 for j in range(N + M - 1)]
	for i in range(N):
		for j in range(M):
			C[i + j] += A[i][j]
			T[i + j] += 1
	for i in range((M + N + 1) // 2 - 1):
		r = C[i] + C[-i - 1]
		if r > T[i]:
			result += 2 * T[i] - r
		else:
			result += r
	print(result)


t = int(input())
import math
for _ in range(t):
	(n, m) = map(int, input().split())
	mat = []
	for i in range(n):
		l = list(map(int, input().split()))
		mat.append(l)
	adj = {}
	for i in range(1, n + 1):
		for j in range(1, m + 1):
			adj[i, j] = []
	for i in range(1, n + 1):
		for j in range(1, m + 1):
			if i < n:
				adj[i, j].append((i + 1, j))
			if j < m:
				adj[i, j].append((i, j + 1))
	ans = 0
	levels = {0: [mat[0][0]]}
	queue = [(1, 1)]
	vis = {}
	d = {}
	d[1, 1] = 0
	while len(queue) != 0:
		s = queue.pop(0)
		l = []
		for i in adj[s]:
			if i not in vis:
				vis[i] = True
				d[i] = d[s] + 1
				try:
					levels[d[s] + 1].append(mat[i[0] - 1][i[1] - 1])
				except:
					levels[d[s] + 1] = [mat[i[0] - 1][i[1] - 1]]
				queue.append(i)
	ans = 0
	for i in range(0, math.ceil((m + n - 2) / 2)):
		if m + n - 2 - i != i:
			a = levels[i]
			a.extend(levels[m + n - 2 - i])
			o = 0
			e = 0
			for i in a:
				if i == 1:
					o += 1
				else:
					e += 1
			ans += min(o, e)
	print(ans)


import sys
import math

def get():
	return int(sys.stdin.readline().strip())

def geti():
	return map(int, sys.stdin.readline().strip().split())

def getli():
	return list(map(int, sys.stdin.readline().strip().split()))
for _ in range(get()):
	(n, m) = geti()
	A = []
	for i in range(n):
		a = getli()
		A.append(a)
	Len = n + m - 1
	ans = 0
	for dist in range(Len // 2):
		(l0, l1, r0, r1) = (0, 0, 0, 0)
		for i in range(n):
			for j in range(m):
				if i + j == dist:
					if A[i][j]:
						l1 += 1
					else:
						l0 += 1
				if n - 1 - i + m - 1 - j == dist:
					if A[i][j]:
						r1 += 1
					else:
						r0 += 1
		ans += min(l0 + r0, l1 + r1)
	print(ans)


import os
import sys
import io
import math

def diagonalOrder(matrix, ROW, COL):
	s = []
	for line in range(1, ROW + COL):
		start_col = max(0, line - ROW)
		count = min(line, COL - start_col, ROW)
		l = []
		for j in range(0, count):
			l.append(matrix[min(ROW, line) - j - 1][start_col + j])
		s.append(l)
	return s
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	matrix = []
	for i in range(n):
		matrix.append(list(map(int, input().split())))
	s = diagonalOrder(matrix, n, m)
	if len(s) % 2 == 1:
		a = s[:len(s) // 2]
		b = s[len(s) // 2 + 1:][::-1]
	else:
		a = s[:len(s) // 2]
		b = s[len(s) // 2:][::-1]
	answer = 0
	for (i, j) in zip(a, b):
		answer += min(abs(i.count(0) + j.count(0)), abs(i.count(1) + j.count(1)))
	print(answer)


from sys import *
input = stdin.readline
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	a = []
	for _ in range(n):
		b = list(map(int, input().split()))
		a.append(b)
	sn = 0
	if a[0][0] != a[n - 1][m - 1]:
		sn += 1
		a[0][0] = 0
		a[n - 1][m - 1] = 0
	q1 = [(0, 0)]
	q2 = [(n - 1, m - 1)]
	(x1, y1) = ([0, 1], [1, 0])
	(x2, y2) = ([-1, 0], [0, -1])
	level = 0
	while q1 and q2:
		l1 = set()
		while q1:
			(c, d) = q1.pop()
			for i in range(2):
				(c1, d1) = (c + x1[i], d + y1[i])
				if 0 <= c1 <= n - 1 and 0 <= d1 <= m - 1:
					l1.add((c1, d1))
		l2 = set()
		while q2:
			(c, d) = q2.pop()
			for i in range(2):
				(c2, d2) = (c + x2[i], d + y2[i])
				if 0 <= c2 <= n - 1 and 0 <= d2 <= m - 1:
					l2.add((c2, d2))
		q1 = list(l1)
		q2 = list(l2)
		s = set()
		s = s.union(l1 - l2, l2 - l1)
		s = list(s)
		(zero, one) = (0, 0)
		for i in range(len(s)):
			(u, v) = (s[i][0], s[i][1])
			if a[u][v] == 0:
				zero += 1
			else:
				one += 1
		if zero > one:
			ch = 0
		else:
			ch = 1
		for i in range(len(s)):
			(u, v) = (s[i][0], s[i][1])
			if a[u][v] != ch:
				a[u][v] = (a[u][v] + 1) % 2
				sn += 1
	print(sn)


cases = int(input())
for case in range(cases):
	(n, m) = map(int, input().split())
	array = []
	counter = 0
	for i in range(n):
		row = list(input().split())
		array.append(row)
	for s in range(m + n):
		counter0 = 0
		counter1 = 0
		if s < m + n - s - 2:
			for i in range(n):
				for j in range(m):
					if i + j == s or i + j == m + n - s - 2:
						if array[i][j] == '0':
							counter0 = counter0 + 1
						else:
							counter1 = counter1 + 1
		counter = counter + min(counter0, counter1)
	print(counter)


from __future__ import division, print_function
import sys
if sys.version_info[0] < 3:
	from __builtin__ import xrange as range
	from future_builtins import ascii, filter, hex, map, oct, zip
import os, sys, bisect, copy
from collections import defaultdict, Counter, deque
if os.path.exists('in.txt'):
	sys.stdin = open('in.txt', 'r')
if os.path.exists('out.txt'):
	sys.stdout = open('out.txt', 'w')

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

def mapi(arg=0):
	return map(int if arg == 0 else str, input().split())
for _ in range(int(input())):
	(n, m) = mapi()
	mat = []
	res = 0
	for i in range(n):
		mat.append(list(mapi()))
	for k in range((n + m) // 2):
		cnt1 = 0
		cnt2 = 0
		cnt = 0
		for i in range(k + 1):
			if i < n and k - i < m:
				cnt1 += mat[i][k - i] == 1
				cnt2 += mat[i][k - i] == 0
				cnt += 1
		for i in range(k + 1):
			if i < n and k - i < m:
				cnt1 += mat[n - i - 1][m - k + i - 1] == 1
				cnt2 += mat[n - i - 1][m - k + i - 1] == 0
				cnt += 1
		if k == (n + m - 1) // 2:
			continue
		res += min(cnt1, cnt2)
	print(res)


from __future__ import division, print_function
import itertools
import sys
import os
from io import BytesIO, IOBase
if sys.version_info[0] < 3:
	input = raw_input
	range = xrange
	filter = itertools.ifilter
	map = itertools.imap
	zip = itertools.izip

def is_it_local():
	script_dir = str(os.getcwd()).split('/')
	username = 'dipta007'
	return username in script_dir

def READ(fileName):
	if is_it_local():
		sys.stdin = open(f'./{fileName}', 'r')
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')
if not is_it_local():
	(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
	input = lambda : sys.stdin.readline().rstrip('\r\n')

def input1(type=int):
	return type(input())

def input2(type=int):
	[a, b] = list(map(type, input().split()))
	return (a, b)

def input3(type=int):
	[a, b, c] = list(map(type, input().split()))
	return (a, b, c)

def input_array(type=int):
	return list(map(type, input().split()))

def input_string():
	s = input()
	return list(s)

def main():
	t = input1()
	for ci in range(t):
		(n, m) = input2()
		mat = []
		for i in range(n):
			now = input_array()
			mat.append(now)
		k = max(n, m) // 2 + n * m % 2
		res = 0
		if m >= n:
			for i in range(0, m):
				(sr, sc) = (0, i)
				(lr, lc) = (n - 1, m - i - 1)
				if sr - lr == lc - sc:
					break
				(z, o) = (0, 0)
				while sr < n and sc >= 0:
					if mat[sr][sc] == 0:
						z += 1
					elif mat[sr][sc] == 1:
						o += 1
					mat[sr][sc] = -1
					sr += 1
					sc -= 1
				while lr >= 0 and lc < m:
					if mat[lr][lc] == 0:
						z += 1
					elif mat[lr][lc] == 1:
						o += 1
					mat[lr][lc] = -1
					lr -= 1
					lc += 1
				tot = z + o
				now = tot - max(z, o)
				res += now
		else:
			for i in range(0, n):
				(sr, sc) = (i, 0)
				(lr, lc) = (n - i - 1, m - 1)
				if sr - lr == lc - sc:
					break
				(z, o) = (0, 0)
				while sr >= 0 and sc < m:
					if mat[sr][sc] == 0:
						z += 1
					elif mat[sr][sc] == 1:
						o += 1
					mat[sr][sc] = -1
					sr -= 1
					sc += 1
				while lr < n and lc >= 0:
					if mat[lr][lc] == 0:
						z += 1
					elif mat[lr][lc] == 1:
						o += 1
					mat[lr][lc] = -1
					lr += 1
					lc -= 1
				tot = z + o
				now = tot - max(z, o)
				res += now
		print(res)
	pass
READ('in.txt')
main()


from sys import stdin
from collections import deque
mod = 10 ** 9 + 7
import sys
import random
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
from itertools import permutations
from math import factorial as f

def ncr(n, r, p):
	num = den = 1
	for i in range(r):
		num = num * (n - i) % p
		den = den * (i + 1) % p
	return num * pow(den, p - 2, p) % p
import sys
t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	la = []
	for i in range(n):
		k = list(map(int, input().split()))
		la.append(k)
	(i, j) = (0, 0)
	(x, y) = (n - 1, m - 1)
	cnt = 0
	ha = n - 1
	ans = 0
	if n >= m:
		cnt = 0
		ha = n - 1
		while cnt < ceil((n + m - 1) // 2):
			hash = defaultdict(int)
			while i >= 0 and j < m:
				hash[la[i][j]] += 1
				i -= 1
				j += 1
			while x <= n - 1 and y >= 0:
				hash[la[x][y]] += 1
				x += 1
				y -= 1
			(a, b) = (hash[0], hash[1])
			ans += min(a, b)
			cnt += 1
			ha -= 1
			i = cnt
			x = ha
			j = 0
			y = m - 1
	else:
		cnt = 0
		ha = m - 1
		while cnt < ceil((n + m - 1) // 2):
			hash = defaultdict(int)
			while j >= 0 and i < n:
				hash[la[i][j]] += 1
				i += 1
				j -= 1
			while y <= m - 1 and x >= 0:
				hash[la[x][y]] += 1
				x -= 1
				y += 1
			(a, b) = (hash[0], hash[1])
			ans += min(a, b)
			cnt += 1
			ha -= 1
			j = cnt
			y = ha
			i = 0
			x = n - 1
	print(ans)


import sys
input = lambda : sys.stdin.readline().rstrip()
inp = sys.stdin.buffer.readline

def I():
	return list(map(int, inp().split()))
for _ in range(int(input())):
	(n, m) = [int(i) for i in input().split()]
	a = []
	for i in range(n):
		a.append([int(i) for i in input().split()])
	ans = [[] for i in range(m + n - 1)]
	for i in range(n):
		for j in range(m):
			ans[i + j].append(a[i][j])
	val = 0
	for i in range(len(ans) // 2):
		val += min(ans[i].count(1) + ans[-(i + 1)].count(1), ans[i].count(0) + ans[-(i + 1)].count(0))
	print(val)


T = int(input())

def solve():
	(n, m) = list(map(int, input().split()))
	mat = []
	for i in range(n):
		li = list(map(int, input().split()))
		mat.append(li)
	count = 0
	for dist in range(int((n + m - 1) / 2)):
		count_0 = 0
		count_1 = 0
		if dist != int((n + m - 1) / 2):
			for i in range(n):
				j = dist - i
				if j < m and j >= 0:
					if mat[i][j] == 0:
						count_0 += 1
					else:
						count_1 += 1
					if mat[n - i - 1][m - j - 1] == 0:
						count_0 += 1
					else:
						count_1 += 1
		count += count_0 if count_0 < count_1 else count_1
	print(count)
for _ in range(T):
	solve()


test = int(input())
for _ in range(test):
	(n, m) = map(int, input().split())
	mat = []
	for i in range(n):
		col = list(map(int, input().split()))
		mat.append(col)
	diag = []
	for i in range(n + m - 1):
		if i < m:
			(r, c) = (0, i)
		else:
			(r, c) = (i - m + 1, m - 1)
		z = 0
		o = 0
		while r < n and c >= 0:
			if mat[r][c] == 1:
				o += 1
			else:
				z += 1
			r += 1
			c -= 1
		diag.append((z, o))
	cost = 0
	l = 0
	r = len(diag) - 1
	while l < r:
		(l0, l1) = diag[l]
		(r0, r1) = diag[r]
		cost += min(l0 + r0, l1 + r1)
		l += 1
		r -= 1
	print(cost)


tll = int(input())
while tll > 0:
	tll -= 1
	(n, m) = map(int, input().split())
	l = []
	for i in range(n):
		temp = list(map(int, input().split()))
		l.append(temp)
	d = {}
	ans = 0
	if l[0][0] != l[n - 1][m - 1]:
		ans += 1
	for i in range(n):
		for j in range(m):
			dist = i + j
			if not (dist == 0 or dist == m + n - 2):
				if dist in d:
					if l[i][j] == 0:
						d[dist][0] += 1
					else:
						d[dist][1] += 1
				else:
					d[dist] = [0, 0]
					if l[i][j] == 0:
						d[dist][0] += 1
					else:
						d[dist][1] += 1
	dd = {}
	for i in range(n):
		for j in range(m):
			dist = n - 1 - i + (m - 1 - j)
			if not (dist == 0 or dist == m + n - 2):
				if dist in dd:
					if l[i][j] == 0:
						dd[dist][0] += 1
					else:
						dd[dist][1] += 1
				else:
					dd[dist] = [0, 0]
					if l[i][j] == 0:
						dd[dist][0] += 1
					else:
						dd[dist][1] += 1
	for i in d:
		if i < (m + n - 1) // 2:
			ans += min(d[i][0] + dd[i][0], d[i][1] + dd[i][1])
	print(ans)


q = int(input())
for z in range(q):
	(n, m) = map(int, input().split(' '))
	res = 0
	matr = [[] for i in range(n)]
	for i in range(n):
		matr[i] = list(map(int, input().split(' ')))
	steps = n + m - 2
	for i in range(steps // 2 + steps % 2):
		am1 = 0
		am0 = 0
		for j in range(i + 1):
			if j < n and i - j < m:
				if matr[j][i - j] == 0:
					am0 += 1
				else:
					am1 += 1
			if n - 1 - j >= 0 and m - 1 - (i - j) >= 0:
				if matr[n - 1 - j][m - 1 - (i - j)] == 0:
					am0 += 1
				else:
					am1 += 1
		res += min(am0, am1)
	print(res)


from collections import defaultdict
from collections import Counter
for t in range(int(input())):
	(n, m) = [int(i) for i in input().split()]
	a = [[int(i) for i in input().split()] for i in range(n)]
	path_len = n + m - 2 + 1
	forward = defaultdict(list)
	cur = 1
	for i in range(m):
		for j in range(min(i + 1, n)):
			forward[cur].append(a[j][i - j])
		cur += 1
	for i in range(1, n):
		for j in range(min(m, n - i)):
			forward[cur].append(a[i + j][m - 1 - j])
		cur += 1
	count = 0
	for i in range(path_len // 2):
		l = forward[i + 1] + forward[path_len - i]
		cnt = Counter(l)
		count += min(cnt[0], cnt[1])
	print(count)


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	a = []
	for i in range(n):
		s = list(map(int, input().split()))
		a.append(s)
	zero = 0
	one = 0
	j = 0
	k = 0
	i = 0
	b = []
	while k < n + m - 1:
		if k < m:
			j = k
			i = 0
		else:
			i = k - m + 1
			j = m - 1
		one = 0
		zero = 0
		while i >= 0 and i < n and (j >= 0) and (j < m):
			if a[i][j] == 1:
				one += 1
			else:
				zero += 1
			i += 1
			j -= 1
		b.append((one, zero))
		k += 1
	s = 0
	e = n + m - 2
	ans = 0
	while s < e:
		ans += min(b[s][0] + b[e][0], b[s][1] + b[e][1])
		s += 1
		e -= 1
	print(ans)


for _ in range(int(input())):
	(n, m) = input().split()
	n = int(n)
	m = int(m)
	l = []
	for i in range(n):
		l.append(list(map(int, input().split())))
	ans = 0
	temp = [[0, 0] for i in range(n + m - 1)]
	for i in range(n):
		for j in range(m):
			temp[i + j][l[i][j]] += 1
	low = 0
	high = n + m - 2
	while low < high:
		ans += min(temp[low][0] + temp[high][0], temp[low][1] + temp[high][1])
		low += 1
		high -= 1
	print(ans)


import collections
from functools import lru_cache

def read():
	return input().strip()

def readInt():
	return int(input().strip())

def readList():
	return list(map(int, input().strip().split()))

def solve(n, m, grid):
	diagonals = collections.defaultdict(list)
	for i in range(n):
		for j in range(m):
			diagonals[i + j].append(grid[i][j])
	keys = list(diagonals.keys())
	keyLen = len(keys)
	ans = 0
	for i in range(keyLen // 2):
		(one, two) = (keys[i], keys[keyLen - i - 1])
		(one, two) = (diagonals[one], diagonals[two])
		(oneCountOne, oneCountTwo) = (sum(one), sum(two))
		(zeroCountOne, zeroCountTwo) = (len(one) - oneCountOne, len(two) - oneCountTwo)
		ones = oneCountOne + oneCountTwo
		zeroes = zeroCountOne + zeroCountTwo
		ans += min(ones, zeroes)
	return ans
t = readInt()
for i in range(t):
	[n, m] = readList()
	grid = []
	for _ in range(n):
		grid.append(readList())
	print(solve(n, m, grid))


t = int(input())
while t != 0:
	t -= 1
	(n, m) = map(int, input().split())
	lt = [[0, 0] for _ in range(n + m - 1)]
	for i in range(n):
		s = [int(x) for x in input().split()]
		for j in range(m):
			p = s[j]
			lt[i + j][p] += 1
	ans = 0
	for i in range(n + m - 1):
		j = n + m - 2 - i
		if i <= j:
			continue
		ans += min(lt[i][0] + lt[j][0], lt[i][1] + lt[j][1])
	print(ans)


t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	A = [list(map(int, input().split())) for i in range(n)]
	B = [[0, 0] for i in range(n + m - 1)]
	for i in range(n):
		for j in range(m):
			B[i + j][A[i][j]] = B[i + j][A[i][j]] + 1
	ans = 0
	l = n + m - 1
	for i in range(l // 2):
		ans = ans + min(B[i][0] + B[l - i - 1][0], B[i][1] + B[l - i - 1][1])
	print(ans)


from sys import stdin
from collections import deque
for _ in range(int(stdin.readline())):
	(l, w) = map(int, stdin.readline().strip().split())
	groups = [''] * (w - 1)
	for i in range(l):
		row = stdin.readline().strip().split()
		for j in range(w - 1):
			groups[j + i] += row[j]
		groups.append(row[w - 1])
	ans = 0
	for i in range(len(groups) // 2):
		s = groups[i] + groups[-(i + 1)]
		(k, p) = (s.count('0'), s.count('1'))
		if k < p:
			ans += k
		else:
			ans += p
	print(ans)


import sys
sys.setrecursionlimit(10 ** 6)
int1 = lambda x: int(x) - 1
p2D = lambda x: print(*x, sep='\n')

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

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

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

def LLI(rows_number):
	return [LI() for _ in range(rows_number)]

def SI():
	return sys.stdin.readline()[:-1]

def main():
	for _ in range(II()):
		(h, w) = MI()
		aa = LLI(h)
		s = h + w - 1
		cnt = [[0, 0] for _ in range(s)]
		for i in range(h):
			for j in range(w):
				cnt[i + j][aa[i][j]] += 1
		ans = 0
		for i in range(s // 2):
			c0 = cnt[i][0] + cnt[s - 1 - i][0]
			c1 = cnt[i][1] + cnt[s - 1 - i][1]
			ans += min(c0, c1)
		print(ans)
main()


def main():
	for _ in range(int(input())):
		(n, m) = map(int, input().split())
		l = [list(map(int, input().split())) for i in range(n)]
		l1 = [[] for i in range(n + m - 1)]
		for i in range(n):
			for j in range(m):
				l1[min(i + j, n - 1 - i + m - 1 - j)].append(l[i][j])
		s = 0
		for i in range((n + m - 1) // 2):
			s += min(l1[i].count(0), l1[i].count(1))
		print(s)
main()


for _ in range(int(input())):
	A = []
	C = []
	(n, m) = map(int, input().split())
	for i in range(n):
		B = list(map(int, input().split()))
		A.append(B)
	for i in range(n + m - 1):
		C.append([])
		for j in range(i + 1):
			if i - j < n and j < m:
				C[-1].append(A[i - j][j])
	Ans = 0
	for i in range(len(C) // 2):
		Ans += min(sum(C[i]) + sum(C[-i - 1]), len(C[i]) + len(C[-1 - i]) - sum(C[i]) - sum(C[-i - 1]))
	print(Ans)


def ispis(a, r, s):
	print()
	for i in range(r):
		for j in range(s):
			print(a[i][j], end=' ')
		print()
from random import randint
t = int(input())
for i in range(t):
	(r, s) = map(int, input().split())
	a = []
	for i in range(r):
		x = list(map(int, input().split()))
		a.append(x)
	b = []
	for i in range(r + s - 1):
		b = b + [0]
	for i in range(r):
		for j in range(s):
			if a[i][j] == 1:
				b[i + j] += 1
	x = 0
	u = min(r, s)
	if (r + s - 1) % 2 == 1:
		for i in range((r + s - 2) // 2):
			y = b[i] + b[r + s - 2 - i]
			v = min(i + 1, u)
			x += min(y, 2 * v - y)
	else:
		for i in range((r + s - 2) // 2 + 1):
			y = b[i] + b[r + s - 2 - i]
			v = min(i + 1, u)
			x += min(y, 2 * v - y)
	print(x)


import math
import sys
input = sys.stdin.readline
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	a = []
	for i in range(n):
		p = list(map(int, input().split()))
		a.append(p)
	diag = n + m - 1
	null = [0] * diag
	one = [0] * diag
	i = 0
	j = 0
	k = 0
	while j < m:
		tempi = i
		tempj = j
		while tempi < n and tempj >= 0:
			if a[tempi][tempj] == 1:
				one[k] += 1
			else:
				null[k] += 1
			tempi += 1
			tempj -= 1
		j += 1
		k += 1
	j -= 1
	i += 1
	while i < n:
		tempi = i
		tempj = j
		while tempi < n and tempj >= 0:
			if a[tempi][tempj] == 1:
				one[k] += 1
			else:
				null[k] += 1
			tempi += 1
			tempj -= 1
		i += 1
		k += 1
	ans = 0
	for t in range(diag // 2):
		ones = one[t] + one[diag - 1 - t]
		nulls = null[t] + null[diag - 1 - t]
		ans += min(ones, nulls)
	print(ans)


import sys
input = sys.stdin.readline
t = int(input())
for _ in range(t):
	(n, m) = list(map(int, input().split()))
	a = [list(map(int, input().split())) for i in range(n)]
	ptn = n + m - 2
	cnt = 0
	ans = []
	for length in range(n + m + 10):
		tmp = []
		for i in range(length + 1):
			j = length - i
			if 0 <= i < n and 0 <= j < m:
				tmp.append(a[i][j])
		if tmp:
			ans.append(tmp)
	len_ans = len(ans)
	res = 0
	for i in range(len_ans // 2):
		cnt = [0, 0]
		for val in ans[i]:
			cnt[val] += 1
		for val in ans[-i - 1]:
			cnt[val] += 1
		res += min(cnt)
	print(res)


import sys
input = sys.stdin.readline
for cas in range(int(input())):
	(r, c) = map(int, input().split())
	mtrx = []
	for i in range(r):
		a = list(map(int, input().split()))
		mtrx.append(a)
	edge = r + c
	minChng = [[0 for col in range(2)] for row in range(edge)]
	for i in range(r):
		for j in range(c):
			if mtrx[i][j] == 0:
				minChng[i + j + 1][0] += 1
			else:
				minChng[i + j + 1][1] += 1
	i = 1
	ans = 0
	edge -= 1
	while i < edge:
		ans += min(minChng[i][0] + minChng[edge][0], minChng[i][1] + minChng[edge][1])
		i += 1
		edge -= 1
	print(ans)


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	matrix = [[int(i) for i in input().split()] for ___ in range(n)]
	path_length = (n + m - 1) // 2
	column = 0
	collisions = 0
	for step in range(path_length):
		(zeros, ones) = (0, 0)
		row = 0 if step < m else step - m + 1
		for col in range(column, -1, -1):
			if matrix[row][col] == 1:
				ones += 1
			else:
				zeros += 1
			if matrix[-row - 1][-col - 1] == 1:
				ones += 1
			else:
				zeros += 1
			row += 1
			if row == n:
				break
		column = min(column + 1, m - 1)
		collisions += zeros if zeros < ones else ones
	print(collisions)


def main():
	import sys
	sys.setrecursionlimit(10 ** 6)
	input = sys.stdin.readline
	t = int(input())
	for _ in range(t):
		(n, m) = [int(x) for x in input().strip().split()]
		one = [0] * ((n + m - 1) // 2 + (n + m - 1) % 2)
		cnt = [0] * ((n + m - 1) // 2 + (n + m - 1) % 2)
		g = [0] * n
		for ni in range(n):
			g[ni] = [int(x) for x in input().strip().split()]
		for (ni, nl) in enumerate(g):
			for (mi, m_) in enumerate(nl):
				if m_:
					one[min(ni + mi, n - 1 + (m - 1) - (ni + mi))] += 1
				cnt[min(ni + mi, n - 1 + (m - 1) - (ni + mi))] += 1
		ans = 0
		for i in range((n + m - 1) // 2):
			ans += min(one[i], cnt[i] - one[i])
		print(ans)
main()


import sys
import os
import time
import collections
from collections import Counter, deque
import itertools
import math
import timeit
import random
import string
import io

def sieve(n):
	if n < 2:
		return list()
	prime = [True for _ in range(n + 1)]
	p = 3
	while p * p <= n:
		if prime[p]:
			for i in range(p * 2, n + 1, p):
				prime[i] = False
		p += 2
	r = [2]
	for p in range(3, n + 1, 2):
		if prime[p]:
			r.append(p)
	return r

def divs(n, start=1):
	divisors = []
	for i in range(start, int(math.sqrt(n) + 1)):
		if n % i == 0:
			if n / i == i:
				divisors.append(i)
			else:
				divisors.extend([i, n // i])
	return divisors

def divn(n, primes):
	divs_number = 1
	for i in primes:
		if n == 1:
			return divs_number
		t = 1
		while n % i == 0:
			t += 1
			n //= i
		divs_number *= t

def flin(d, x, default=-1):
	left = right = -1
	for i in range(len(d)):
		if d[i] == x:
			if left == -1:
				left = i
			right = i
	if left == -1:
		return (default, default)
	else:
		return (left, right)

def gcd(x, y):
	while y:
		(x, y) = (y, x % y)
	return x

def ceil(n, k):
	return n // k + (n % k != 0)

def ii():
	return int(input())

def mi():
	return map(int, input().split())

def li():
	return list(map(int, input().split()))

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

def prr(a, sep=' ', end='\n'):
	print(sep.join(map(str, a)), end=end)

def dd():
	return collections.defaultdict(int)

def ddl():
	return collections.defaultdict(list)
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline

def diagonalOrder(matrix, ROW, COL):
	s = []
	for line in range(1, ROW + COL):
		start_col = max(0, line - ROW)
		count = min(line, COL - start_col, ROW)
		l = []
		for j in range(0, count):
			l.append(matrix[min(ROW, line) - j - 1][start_col + j])
		s.append(l)
	return s
for _ in range(int(input())):
	(n, m) = mi()
	matrix = []
	for i in range(n):
		matrix.append(list(map(int, input().split())))
	s = diagonalOrder(matrix, n, m)
	if len(s) % 2 == 1:
		a = s[:len(s) // 2]
		b = s[len(s) // 2 + 1:][::-1]
	else:
		a = s[:len(s) // 2]
		b = s[len(s) // 2:][::-1]
	answer = 0
	for (i, j) in zip(a, b):
		answer += min(abs(i.count(0) + j.count(0)), abs(i.count(1) + j.count(1)))
	print(answer)


for i in range(int(input())):
	(n, m) = map(int, input().split())
	a = []
	for i in range(n):
		k = list(map(int, input().split()))
		a.append(k[:])
	(k1, k2) = (2, n + m)
	count = 0
	for i in range((n + m - 1) // 2):
		l = [0, 0]
		for pi in range(max(1, k1 - m), min(k1, n + 1)):
			pj = k1 - pi
			l[a[pi - 1][pj - 1]] += 1
		for pi in range(max(k2 - m, 1), min(k2, n + 1)):
			pj = k2 - pi
			l[a[pi - 1][pj - 1]] += 1
		count += l[0] + l[1] - max(l)
		k1 += 1
		k2 -= 1
	print(count)


import sys
input = sys.stdin.readline
ans = []
for kek in range(int(input())):
	(n, m) = map(int, input().split())
	a = []
	for i in range(n):
		a.append(list(map(int, input().split())))
	d = dict()
	diag = dict()
	for i in range(0, n + m - 1):
		d[i] = 0
		diag[i] = 0
	for i in range(n):
		for j in range(m):
			d[i + j] += a[i][j]
			diag[i + j] += 1
	L = n - 1 + m - 1
	xxxx = 0
	for i in range(n + m - 1):
		if i == L - i:
			continue
		x = d[i] + d[L - i]
		y = diag[i] + diag[L - i]
		xxxx += min(x, y - x)
	ans.append(xxxx // 2)
print(*ans, sep='\n')


from collections import defaultdict
for _ in range(int(input())):
	(n, m) = [int(y) for y in input().split()]
	a = list()
	for i in range(n):
		a.append([int(y) for y in input().split()])
	d = defaultdict(lambda : [])
	for i in range(n):
		for j in range(m):
			d[i + j].append(a[i][j])
	(i, j, result) = (0, len(d) - 1, 0)
	while j > i:
		lst = d[i] + d[j]
		(zeros, ones) = (lst.count(0), lst.count(1))
		result += min(zeros, ones)
		i += 1
		j -= 1
	print(result)


from sys import stdin, stdout
int_in = lambda : int(stdin.readline())
arr_in = lambda : [int(x) for x in stdin.readline().split()]
mat_in = lambda rows: [arr_in() for y in range(rows)]
str_in = lambda : stdin.readline().strip()
out = lambda o: stdout.write('{}\n'.format(o))
arr_out = lambda o: out(' '.join(map(str, o)))
bool_out = lambda o: out('YES' if o else 'NO')
tests = lambda : range(1, int_in() + 1)
case_out = lambda i, o: out('Case #{}: {}'.format(i, o))

def solve(n, m, matrix):
	buckets = [[0, 0] for _ in range(n + m - 1)]
	for i in range(n):
		for j in range(m):
			buckets[i + j][matrix[i][j]] += 1
	result = 0
	for i in range(len(buckets) // 2):
		result += min(buckets[i][0] + buckets[~i][0], buckets[i][1] + buckets[~i][1])
	return result
for i in tests():
	(n, m) = arr_in()
	matrix = mat_in(n)
	out(solve(n, m, matrix))


for t in range(int(input())):
	(n, m) = map(int, input().split())
	arr = [[0, 0] for i in range(n + m - 1)]
	ans = 0
	for i in range(n):
		l = list(map(int, input().split()))
		for j in range(m):
			arr[i + j][l[j]] += 1
	for k in range((n + m - 1) // 2):
		ans += min(arr[k][0] + arr[n + m - 2 - k][0], arr[k][1] + arr[n + m - 2 - k][1])
	print(ans)


from collections import defaultdict
t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	nums = defaultdict(list)
	for y in range(n):
		row = list(map(int, input().split()))
		for x in range(m):
			nums[min(y + x, n - y - 1 + m - x - 1)].append(row[x])
	total = 0
	for (tot, vals) in nums.items():
		s = sum(vals)
		l = len(vals)
		if tot == max(nums.keys()) and (n + m - 1) % 2 == 1:
			continue
		total += min(s, l - s)
	print(total)


from fractions import Fraction
import bisect
import os
from collections import Counter
import bisect
from collections import defaultdict
import math
import random
import heapq as hq
from math import sqrt
import sys
from functools import reduce, cmp_to_key
from collections import deque
import threading
from itertools import combinations
from io import BytesIO, IOBase
from itertools import accumulate
from queue import Queue
sys.setrecursionlimit(200000)

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

def iinput():
	return int(input())

def tinput():
	return input().split()

def rinput():
	return map(int, tinput())

def rlinput():
	return list(rinput())
mod = int(1000000000.0) + 7

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)))
t = 1
t = iinput()
for i in range(t):
	(n, m) = rinput()
	mat = []
	for i in range(n):
		mat.append(rlinput())
	d = defaultdict(list)
	for i in range((n + m - 1) // 2 + 2):
		d[i] = [0, 0]
	for i in range(n):
		for j in range(m):
			d[min(i + j, n + m - i - j - 2)][mat[i][j]] += 1
	ans = 0
	for i in range((n + m - 1) // 2):
		ans += min(d[i])
	print(ans)


t = int(input())
for _ in range(t):
	(n, m) = [int(x) for x in input().split()]
	a = []
	k = (n + m) // 2
	cnt = [[], []]
	cnt[0] = [0 for _ in range(k)]
	cnt[1] = [0 for _ in range(k)]
	for i in range(n):
		a.append([int(x) for x in input().split()])
	for i in range(n):
		for j in range(m):
			if i + j < k:
				c = i + j
			else:
				c = n - 1 + m - 1 - (i + j)
			cnt[a[i][j]][c] += 1
	res = 0
	for i in range(k):
		if (n + m) % 2 == 0 and i == k - 1:
			continue
		res += min(cnt[0][i], cnt[1][i])
	print(res)


from collections import defaultdict
T = int(input())
for t in range(T):
	(n, m) = map(int, input().split())
	matrix = [list(map(int, input().split())) for _ in range(n)]
	l = n - 1 + m - 1
	pos = [[0, 0] for i in range(n * m)]
	for (i, r) in enumerate(matrix):
		for (j, c) in enumerate(r):
			if i + j == l - (i + j):
				continue
			idx = min(i + j, l - (i + j))
			pos[idx][c] += 1
	print(sum((min(freq) for freq in pos)))


import math

def solve(m, n, matrix):
	max_dis = n + m - 2
	ans = 0
	if matrix[0][0] != matrix[m - 1][n - 1]:
		ans += 1
	prev = [(0, 0), (m - 1, n - 1)]
	seen = set()
	seen.add((0, 0))
	seen.add((m - 1, n - 1))
	for i in range(1, math.ceil(max_dis / 2)):
		curr = []
		for (x, y) in prev:
			if 0 <= x + 1 < m and (x + 1, y) not in seen:
				curr.append((x + 1, y))
				seen.add((x + 1, y))
			if 0 <= x - 1 < m and (x - 1, y) not in seen:
				curr.append((x - 1, y))
				seen.add((x - 1, y))
			if 0 <= y + 1 < n and (x, y + 1) not in seen:
				curr.append((x, y + 1))
				seen.add((x, y + 1))
			if 0 <= y - 1 < n and (x, y - 1) not in seen:
				curr.append((x, y - 1))
				seen.add((x, y - 1))
		(one_count, zero_count) = (0, 0)
		for (x, y) in curr:
			if matrix[x][y] == '0':
				zero_count += 1
			else:
				one_count += 1
		ans += min(one_count, zero_count)
		prev = curr
	return ans

def main():
	t = int(input())
	test_case_number = 1
	while test_case_number <= t:
		(n, m) = map(int, input().split())
		matrix = []
		for j in range(n):
			row = input()
			row = row.replace(' ', '')
			matrix.append(list(row))
		print(solve(n, m, matrix))
		test_case_number += 1
main()


import sys
reader = (s.rstrip() for s in sys.stdin)
input = reader.__next__
t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	grid = [[int(x) for x in input().split()] for y in range(n)]
	pathLength = n + m - 1
	dist = [[] for x in range(pathLength)]
	for x in range(n):
		for y in range(m):
			dist[x + y].append(grid[x][y])
	i = 0
	j = pathLength - 1
	ans = 0
	while i < j:
		temp = dist[i] + dist[j]
		ones = temp.count(0)
		zeros = len(temp) - ones
		ans += min(ones, zeros)
		i += 1
		j -= 1
	print(ans)


from sys import stdin, stdout
import math
from random import randint
t = int(stdin.readline())
for _ in range(t):
	(n, m) = map(int, stdin.readline().split())
	g = []
	for _ in range(n):
		g.append(list(map(int, stdin.readline().strip().split())))
	ans = 0
	for i in range((n + m - 1) // 2):
		cnt = [0, 0]
		(r, c) = (0, i)
		for _ in range(30):
			if 0 <= r < n and 0 <= c < m:
				cnt[g[r][c]] += 1
			r += 1
			c -= 1
		(r, c) = (n - 1, m - 1 - i)
		for _ in range(30):
			if 0 <= r < n and 0 <= c < m:
				cnt[g[r][c]] += 1
			r -= 1
			c += 1
		ans += min(cnt)
	print(ans)


from collections import deque
t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	l = [list(map(int, input().split())) for i in range(n)]
	count = [[0] * 2 for i in range(n + m - 1)]
	q = deque([])
	count[0][l[0][0]] += 1
	q.append((0, 0, 0))
	while q:
		(bx, by, dis) = q.popleft()
		if bx + 1 < n and l[bx + 1][by] >= 0:
			count[dis + 1][l[bx + 1][by]] += 1
			l[bx + 1][by] = -1
			q.append((bx + 1, by, dis + 1))
		if by + 1 < m and l[bx][by + 1] >= 0:
			count[dis + 1][l[bx][by + 1]] += 1
			l[bx][by + 1] = -1
			q.append((bx, by + 1, dis + 1))
	ans = 0
	for i in range(len(count) // 2):
		ans += min(count[i][0] + count[-1 - i][0], count[i][1] + count[-1 - i][1])
	print(ans)


def mi():
	return map(int, input().split())
for _ in range(int(input())):
	(n, m) = mi()
	a = [0] * n
	ans = 0
	for i in range(n):
		a[i] = list(mi())
	r1 = [[0] * 2 for i in range(n - 1 + m - 1 + 1)]
	for i in range(n):
		for j in range(m):
			r1[i - 0 + j - 0][a[i][j]] += 1
	for i in range((n - 1 + m - 1) // 2 + 1):
		if i == (n - 1 + m - 1) // 2 and (m + n) % 2 == 0:
			continue
		else:
			ans += min(r1[i][0] + r1[n - 1 + m - 1 - i][0], r1[i][1] + r1[n - 1 + m - 1 - i][1])
	print(ans)


for i in range(int(input())):
	(n, m) = map(int, input().split())
	l = []
	for i in range(n):
		l.append(list(map(int, input().split())))
	p1 = []
	p2 = []
	if m >= n:
		for i in range((m + n - 1) // 2):
			x = [0, i]
			(c1, c2) = (0, 0)
			while 1:
				if l[x[0]][x[1]] == 0:
					c1 += 1
				else:
					c2 += 1
				if x[0] < n - 1 and x[1] > 0:
					x[0] += 1
					x[1] -= 1
				else:
					break
			p1.append([c1, c2])
		for i in range((m + n - 1) // 2):
			x = [n - 1, m - i - 1]
			(c1, c2) = (0, 0)
			while 1:
				if l[x[0]][x[1]] == 0:
					c1 += 1
				else:
					c2 += 1
				if x[0] > 0 and x[1] < m - 1:
					x[0] -= 1
					x[1] += 1
				else:
					break
			p2.append([c1, c2])
	else:
		for i in range((m + n - 1) // 2):
			x = [i, 0]
			(c1, c2) = (0, 0)
			while 1:
				if l[x[0]][x[1]] == 0:
					c1 += 1
				else:
					c2 += 1
				if x[0] > 0 and x[1] < m - 1:
					x[0] -= 1
					x[1] += 1
				else:
					break
			p2.append([c1, c2])
		for i in range((m + n - 1) // 2):
			x = [n - 1 - i, m - 1]
			(c1, c2) = (0, 0)
			while 1:
				if l[x[0]][x[1]] == 0:
					c1 += 1
				else:
					c2 += 1
				if x[0] < n - 1 and x[1] > 0:
					x[0] += 1
					x[1] -= 1
				else:
					break
			p1.append([c1, c2])
	c = 0
	for i in range((m + n - 1) // 2):
		y1 = p1[i][0] + p2[i][0]
		y2 = p1[i][1] + p2[i][1]
		c += min(y1, y2)
	print(c)


t = int(input())
ans = [0] * t
for i in range(t):
	(n, m) = map(int, input().split())
	A = []
	B1 = [0] * (n + m - 1)
	B0 = [0] * (n + m - 1)
	for j in range(n):
		A.append(list(map(int, input().split())))
	for j in range(n):
		for k in range(m):
			if A[j][k] == 0:
				B0[j + k] += 1
			else:
				B1[j + k] += 1
	for j in range((n + m - 1) // 2):
		x = B1[j] + B1[n + m - j - 2]
		y = B0[j] + B0[n + m - j - 2]
		if x >= y:
			ans[i] += y
		else:
			ans[i] += x
for i in range(t):
	print(int(ans[i]))


for t in range(int(input())):
	(n, m) = [int(j) for j in input().split()]
	l = []
	for i in range(n):
		l.append([int(j) for j in input().split()])
	d = [[0, 0] for i in range((n + m - 1) // 2 + 2)]
	for i in range(n):
		for j in range(m):
			x = min(i - 0 + (j - 0), n - 1 - i + (m - 1 - j))
			d[x][l[i][j]] += 1
	ans = 0
	for x in d[:(n + m - 1) // 2]:
		ans += min(x[0], x[1])
	print(ans)


from collections import Counter as ctr
from collections import defaultdict as dd
from sys import stdin, stdout
for t in range(int(stdin.readline().strip())):
	(n, m) = map(int, stdin.readline().strip().split())
	a = []
	for i in range(n):
		temp = list(map(int, stdin.readline().strip().split()))
		a.append(temp.copy())
	d = dd(list)
	for i in range(n):
		for j in range(m):
			d[min(i + j, n + m - i - j - 2)].append(a[i][j])
	c = 0
	for i in d.keys():
		l = len(d[i])
		if (n + m) % 2 == 0:
			if i == (n + m) // 2 - 1:
				continue
		c = c + l - ctr(d[i]).most_common()[0][1]
	stdout.write(str(c) + '\n')


import math
from sys import stdin, stdout
from heapq import heapify, heappop, heappush
import collections
T = int(stdin.readline())
for i in range(T):
	a = []
	(N, M) = list(map(int, stdin.readline().split()))
	for i in range(N):
		a.append(list(map(int, stdin.readline().split())))
	dc = collections.defaultdict(list)
	ans = 0
	for i in range(N):
		for j in range(M):
			(ci, cj) = (N - 1 - i, M - 1 - j)
			if i + j == cj + ci:
				continue
			ind = min(i + j, ci + cj)
			dc[ind].append(a[i][j])
	for (k, v) in dc.items():
		z = v.count(0)
		o = v.count(1)
		if o < z:
			ans += o
		else:
			ans += z
	print(ans)


for k in range(int(input())):
	(n, m) = map(int, input().split())
	a = [list(map(int, input().split())) for i in range(n)]
	l = n + m - 1
	r = [[] for i in range(l)]
	for i in range(n):
		for j in range(m):
			r[i + j].append(a[i][j])
	res = 0
	for i in range(l // 2):
		t = r[i] + r[-1 - i]
		res += min(t.count(1), t.count(0))
	print(res)


import sys
input = sys.stdin.readline
from collections import Counter
t = int(input())
for tests in range(t):
	(n, m) = map(int, input().split())
	M = [list(map(int, input().split())) for i in range(n)]
	A = [[] for i in range(n + m - 1)]
	for i in range(n):
		for j in range(m):
			A[i + j].append(M[i][j])
	ANS = 0
	for k in range((n + m - 1) // 2):
		C = Counter(A[k] + A[-k - 1])
		ANS += min(C[0], C[1])
	print(ANS)


t = int(input())
for _ in range(t):
	(m, n) = map(int, input().split())
	from collections import defaultdict
	store = defaultdict(list)
	mat = []
	for i in range(m):
		temp = list(map(int, input().strip().split()))[:n]
		mat.append(temp)
		for j in range(n):
			x = i + j
			y = m + n - (i + j) - 2
			if x != y:
				store[min(x, y)].append(mat[i][j])
	ans = 0
	for (num, b) in store.items():
		zero = b.count(0)
		ones = b.count(1)
		ans += min(ones, zero)
	print(ans)


t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	g = []
	for i in range(n):
		g.append(list(map(int, input().split())))
	cmps = [[0, 0] for i in range(n + m - 1)]
	for i in range(n):
		for j in range(m):
			cmps[i + j][g[i][j]] += 1
	l = len(cmps)
	ans = 0
	for i in range(l // 2):
		ans += min(cmps[i][0] + cmps[l - i - 1][0], cmps[i][1] + cmps[l - i - 1][1])
	print(ans)


import math
import sys
from itertools import permutations
input = sys.stdin.readline
t = int(input())
for i in range(t):
	(n, m) = map(int, input().split())
	arr = []
	for j in range(n):
		arr.append(list(map(int, input().split())))
	ans = []
	for j in range(n + m - 1):
		ans.append([])
	for j in range(n):
		for k in range(m):
			ans[j + k].append(arr[j][k])
	fin = 0
	for j in range(math.ceil((n + m - 1) / 2)):
		if len(ans) % 2 == 1 and j == math.ceil((n + m - 1) / 2) - 1:
			pass
		else:
			cur = sum(ans[j]) + sum(ans[n + m - 2 - j])
			now = min(cur, len(ans[j]) + len(ans[n + m - 2 - j]) - cur)
			fin += now
	print(fin)


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	arr = [[0] * m for i in range(n)]
	for i in range(n):
		arr[i] = list(map(int, input().split()))
	ans = 0
	brr = []
	for s in range(n + m - 1):
		kek = [0, 0]
		for i in range(n):
			j = s - i
			if not 0 <= j < m:
				continue
			kek[arr[i][j]] += 1
		brr.append(kek)
	for i in range(len(brr) // 2):
		ans += min(brr[i][0] + brr[-i - 1][0], brr[i][1] + brr[-i - 1][1])
	print(ans)


from sys import stdin
from collections import defaultdict as dd
from collections import deque as dq
import itertools as it
from math import sqrt, log, log2
from fractions import Fraction
t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	matrix = []
	for r in range(n):
		row = list(map(int, input().split()))
		matrix.append(row)
	ans = 0
	for dist in range(1 + (m + n - 2) // 2):
		beg = {0: 0, 1: 0}
		end = {0: 0, 1: 0}
		visited = []
		for i in range(min(dist + 1, n)):
			j = dist - i
			if j < m:
				beg[matrix[0 + i][0 + j]] += 1
				end[matrix[n - 1 - i][m - 1 - j]] += 1
				visited.append((i, j))
				visited.append((n - 1 - i, m - 1 - j))
		if len(visited) != 2 * len(set(visited)):
			if beg[0] + end[0] >= beg[1] + end[1]:
				ans += beg[1] + end[1]
			else:
				ans += beg[0] + end[0]
	print(ans)


T = int(input())
for _ in range(T):
	(n, m) = map(int, input().split())
	A = list()
	for _ in range(n):
		A.append(list(map(int, input().split())))
	V = set()
	count = 0
	forward = [[0, 0]]
	backward = [[n - 1, m - 1]]
	V.add((0, 0))
	V.add((n - 1, m - 1))
	while True:
		ones = 0
		zeros = 0
		for (x, y) in forward:
			if A[x][y] == 1:
				ones += 1
			else:
				zeros += 1
		for (x, y) in backward:
			if A[x][y] == 1:
				ones += 1
			else:
				zeros += 1
		count += min(ones, zeros)
		if len(V) == m * n:
			break
		forwardNew = list()
		for (x, y) in forward:
			if x + 1 in range(n) and y in range(m):
				if (x + 1, y) not in V:
					V.add((x + 1, y))
					forwardNew.append([x + 1, y])
			if x in range(n) and y + 1 in range(m):
				if (x, y + 1) not in V:
					V.add((x, y + 1))
					forwardNew.append([x, y + 1])
		if len(V) == m * n:
			break
		backwardNew = list()
		for (x, y) in backward:
			if x - 1 in range(n) and y in range(m):
				if (x - 1, y) not in V:
					V.add((x - 1, y))
					backwardNew.append([x - 1, y])
			if x in range(n) and y - 1 in range(m):
				if (x, y - 1) not in V:
					V.add((x, y - 1))
					backwardNew.append([x, y - 1])
		forward = forwardNew
		backward = backwardNew
	print(count)


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	a = [list(map(int, input().split())) for _ in range(n)]
	ans = 0
	allCnts = []
	for k in range(n + m - 1):
		cnt = [0, 0]
		i = k + 1
		for j in range(n + m):
			i -= 1
			if i < 0 or i >= n or j >= m:
				continue
			cnt[a[i][j]] += 1
		allCnts.append(cnt)
	for i in range(len(allCnts) // 2):
		zeros = allCnts[i][0] + allCnts[-i - 1][0]
		ones = allCnts[i][1] + allCnts[-i - 1][1]
		ans += min(zeros, ones)
	print(ans)


import sys
import collections

def get_rows(grid):
	return [[c for c in r] for r in grid]

def get_cols(grid):
	return zip(*grid)

def get_backward_diagonals(grid):
	b = [None] * (len(grid) - 1)
	grid = [b[i:] + r + b[:i] for (i, r) in enumerate(get_rows(grid))]
	return [[c for c in r if c is not None] for r in get_cols(grid)]

def get_forward_diagonals(grid):
	b = [None] * (len(grid) - 1)
	grid = [b[:i] + r + b[i:] for (i, r) in enumerate(get_rows(grid))]
	return [[c for c in r if c is not None][::-1] for r in get_cols(grid)]

def diff_arrays(a, b):
	toZero = a.count(1) + b.count(1)
	toOne = a.count(0) + b.count(0)
	return min(toZero, toOne)
t = int(sys.stdin.readline().strip())
for i in range(t):
	(n, m) = list(map(int, sys.stdin.readline().strip().split(' ')))
	grid = []
	for _ in range(n):
		l = list(map(int, sys.stdin.readline().strip().split(' ')))
		grid.append(l)
	diag = get_forward_diagonals(grid)
	cnt = 0
	for i in range(len(diag) // 2):
		cnt += diff_arrays(diag[i], diag[len(diag) - 1 - i])
	print(cnt)


import sys
_INPUT_LINES = sys.stdin.read().splitlines()
input = iter(_INPUT_LINES).__next__
tc = int(input())
for zz in range(tc):
	(sar, col) = map(int, input().split())
	arr = [[0] * col for i in range(sar)]
	cont = [[] for i in range(sar + col)]
	for i in range(sar):
		temp = list(map(int, input().split()))
		for j in range(col):
			arr[i][j] = temp[j]
	for i in range(sar):
		for j in range(col):
			fol = i + j + 1
			cont[fol].append(arr[i][j])
	repe = sar + col - 1
	bare = repe // 2 + 1
	ans = 0
	for i in range(1, bare):
		ele1 = cont[i]
		ele2 = cont[repe - i + 1]
		ones = ele1.count(1) + ele2.count(1)
		zers = ele1.count(0) + ele2.count(0)
		ans += min(ones, zers)
	print(ans)


cases = int(input())
for t in range(cases):
	(n, m) = list(map(int, input().split()))
	a = [list(map(int, input().split())) for i in range(n)]
	b = [[] for i in range(n + m - 1)]
	for i in range(n):
		for j in range(m):
			d = i + j
			b[d].append(a[i][j])
	centre = (n + m - 1) // 2
	output = 0
	for i in range(centre):
		ones = sum(b[i]) + sum(b[n + m - 2 - i])
		total = min(i + 1, n, m) * 2
		output += min(ones, total - ones)
	print(output)


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	ar = [list(map(int, input().split())) for _ in range(n)]
	b = [0] * (n + m - 1)
	for i in range(n):
		for j in range(m):
			b[i + j] += ar[i][j]
	c = min(n, m)
	z = n + m - 1
	a = [0] * (n + m - 1)
	for i in range(n + m - 1):
		a[i] = min([i + 1, z - i, c])
	ans = 0
	i = 0
	j = n + m - 2
	while i <= j:
		k = min(2 * a[i] - b[i] - b[j], b[i] + b[j])
		if i == j:
			break
		ans += k
		i += 1
		j -= 1
	print(ans)


t = int(input())
for case in range(t):
	(n, m) = [int(x) for x in input().split(' ')]
	A = [[int(x) for x in input().split(' ')] for row in range(n)]
	A_dict = {}
	cnt = 0
	if max(m, n) == 2:
		ans = int(A[0][0] != A[1][1])
	else:
		for i in range(n):
			for j in range(m):
				x = min(i + j, n - 1 - i + m - 1 - j)
				if i + j == (m + n - 2) // 2 and (m + n - 1) % 2 == 1:
					pass
				elif x in A_dict.keys():
					A_dict[x] += [A[i][j]]
				else:
					A_dict[x] = [A[i][j]]
		for v in A_dict.values():
			cnt += len(v) - v.count(max(v, key=v.count))
	print(cnt)


t = int(input())
results = []
for case in range(t):
	(n, m) = map(int, input().split())
	matrix = []
	for i in range(n):
		row = list(map(int, input().split()))
		matrix.append(row)
	diag = (n + m - 1) // 2
	count = 0
	for i in range(diag):
		row = i + 1
		d1 = [0, 0]
		d2 = [0, 0]
		diag_length = min(row, n, m)
		start_row = max(0, row - m)
		for j in range(diag_length):
			d1[matrix[start_row + j][min(m, row) - 1 - j]] += 1
			d2[matrix[n - start_row - 1 - j][m - min(m, row) + j]] += 1
		count += min(d1[0] + d2[0], d1[1] + d2[1])
	results.append(count)
for result in results:
	print(result)


t = int(input())
for _ in range(t):
	(n, m) = [int(p) for p in input().split()]
	matrix = []
	for i in range(n):
		matrix.append([int(p) for p in input().split()])
	neigh1 = []
	neigh2 = []
	for i in range((n + m - 1) // 2):
		temp = []
		for j in range(i + 1):
			if j < n and i - j < m:
				temp.append(matrix[j][i - j])
		neigh1.append(temp)
	for i in range(n):
		matrix[i].reverse()
	matrix.reverse()
	for i in range((n + m - 1) // 2):
		temp = []
		for j in range(i + 1):
			if j < n and i - j < m:
				temp.append(matrix[j][i - j])
		neigh2.append(temp)
	cnt = 0
	for i in range(len(neigh1)):
		(a1, a2) = (neigh1[i], neigh2[i])
		cnt1 = neigh1[i].count(1) + neigh2[i].count(1)
		cnt0 = neigh1[i].count(0) + neigh2[i].count(0)
		if cnt1 >= cnt0:
			cnt += cnt0
		else:
			cnt += cnt1
	print(cnt)


import math as mt
import sys, string
input = sys.stdin.readline
from collections import defaultdict
from heapq import heappush, heapify, heappop
L = lambda : list(map(int, input().split()))
Ls = lambda : list(input().split())
M = lambda : map(int, input().split())
I = lambda : int(input())
t = I()
for _ in range(t):
	(n, m) = M()
	l = []
	for i in range(n):
		l.append(L())
	d = defaultdict(int)
	x = defaultdict(int)
	for i in range(n):
		for j in range(m):
			if l[i][j] == 1:
				d[i + j] += 1
			else:
				x[i + j] += 1
	ans = 0
	for i in range((n + m - 1) // 2):
		ans += min(d[i] + d[n + m - i - 2], x[i] + x[n + m - i - 2])
	print(ans)


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	matrix = [list(map(int, input().split())) for __ in range(n)]
	cnt = 0
	diag = [[] for i in range(n + m - 1)]
	for i in range(n):
		for j in range(m):
			diag[i + j].append(matrix[i][j])
	for i in range((n + m - 1) // 2):
		diag[i] = diag[i] + diag[-1 - i]
		cnt += min(diag[i].count(0), diag[i].count(1))
	print(cnt)


from math import *
for i in range(int(input())):
	(n, m) = map(int, input().split())
	l = []
	for i in range(n):
		l1 = list(map(int, input().split()))
		l.append(l1)
	dp1 = {}
	dp2 = {}
	for i in range(0, n + m - 2 + 1):
		dp1[i] = 0
		dp2[i] = 0
	for i in range(n):
		for j in range(m):
			if i + j == int((n + m - 2) / 2) and (n + m - 2) % 2 == 0:
				continue
			if l[i][j] == 0:
				dp1[min(i + j, n + m - 2 - i - j)] += 1
			else:
				dp2[min(i + j, n + m - 2 - i - j)] += 1
	ans = 0
	for i in range(0, n + m - 1):
		if dp1[i] + dp2[i] > 1:
			ans += min(dp1[i], dp2[i])
	print(ans)


from pprint import pprint
num_test = int(input())
all_tests = []
for _ in range(num_test):
	(n, m) = list(map(int, input().strip().split()))
	a_test = []
	for _ in range(n):
		a_row = list(map(int, input().strip().split()))
		a_test.append(a_row)
	all_tests.append(a_test)

def get_diag(mat, diag_no):
	cur_row = 0
	cur_col = diag_no
	diag = []
	while cur_col >= 0:
		try:
			diag.append(mat[cur_row][cur_col])
		except:
			pass
		finally:
			cur_row += 1
			cur_col -= 1
	return diag
for mat in all_tests:
	n = len(mat)
	m = len(mat[0])
	num_diag = n + m - 1
	num_clusters = num_diag // 2
	clusters = []
	for i in range(num_diag):
		diag_i = get_diag(mat, i)
		if i < num_clusters:
			clusters.append(diag_i)
		elif i == (num_diag - 1) / 2:
			continue
		else:
			clusters[num_diag - i - 1] += diag_i
	final_count = 0
	for cluster in clusters:
		num_of_one = sum(cluster)
		num_of_zero = len(cluster) - num_of_one
		final_count += num_of_one if num_of_one < num_of_zero else num_of_zero
	print(final_count)


import sys
input = lambda : sys.stdin.readline().strip()
t = int(input())

def min_cost(a, b):
	v = a.count(0)
	v1 = b.count(0)
	u = a.count(1)
	u1 = b.count(1)
	return min(v + v1, u + u1)
while t:
	t -= 1
	(n, m) = map(int, input().split())
	mat = []
	for i in range(n):
		mat.append(list(map(int, input().split())))
	diags = [[] for _ in range(n + m - 1)]
	for i in range(1, n + m):
		col = max(0, i - n)
		count = min(i, m - col, n)
		for j in range(count):
			diags[i - 1].append(mat[min(n, i) - j - 1][col + j])
	ans = 0
	for i in range(len(diags) // 2):
		ans += min_cost(diags[i], diags[len(diags) - 1 - i])
	print(ans)


from sys import stdin, stdout
import sys
from math import *
input = stdin.buffer.readline
for __ in range(int(input())):
	(n, m) = map(int, input().split())
	mat = []
	for i in range(n):
		mat.append(list(map(int, input().split())))
	d = {}
	for i in range(n):
		for j in range(m):
			if d.get(i + j + 1) == None:
				d[i + j + 1] = [mat[i][j]]
			else:
				d[i + j + 1].append(mat[i][j])
	v = list(d.values())
	ans = 0
	for i in range(len(v) // 2):
		n1 = v[i].count(1)
		n2 = v[-(i + 1)].count(1)
		n = len(v[i])
		ans += min(2 * n - (n1 + n2), 2 * n - (n - n1 + n - n2))
	print(ans)


for i in range(int(input())):
	(n, m) = map(int, input().split())
	l = []
	for i in range(n):
		l.append(list(map(int, input().split())))
	k = (n + m - 1) // 2
	a = 0
	b = 0
	c = n - 1
	d = m - 1
	ans = 0
	while k > 0:
		k -= 1
		tempa = a
		tempb = b
		counta = 0
		countb = 0
		while tempa <= n - 1 and tempb >= 0:
			if l[tempa][tempb] == 0:
				counta += 1
			else:
				countb += 1
			tempa += 1
			tempb -= 1
		if b == m - 1:
			a += 1
		else:
			b += 1
		tempa = c
		tempb = d
		while tempa <= n - 1 and tempb >= 0:
			if l[tempa][tempb] == 0:
				counta += 1
			else:
				countb += 1
			tempa += 1
			tempb -= 1
		ans += min(counta, countb)
		if c == 0:
			d -= 1
		else:
			c -= 1
	print(ans)


import itertools
a = [[0 for _ in range(30)] for x in range(30)]

def walk(a, n, m):
	x = []
	cur = 0
	q = [(0, 0)]
	used = set()
	while cur < len(q):
		(i, j) = q[cur]
		cur += 1
		index = min(n - 1 + (m - 1) - (i + j), i + j)
		x.append((index, a[i][j]))
		if i + 1 < n and (i + 1, j) not in used:
			used.add((i + 1, j))
			q.append((i + 1, j))
		if j + 1 < m and (i, j + 1) not in used:
			used.add((i, j + 1))
			q.append((i, j + 1))
	return x

def process():
	[n, m] = list(map(int, input().split(' ')))
	for i in range(n):
		for (j, val) in enumerate(map(int, input().split(' '))):
			a[i][j] = val
	indices = walk(a, n, m)
	c = 0
	for (k, g) in itertools.groupby(sorted(indices), lambda x: x[0]):
		if (n - 1 + (m - 1)) % 2 == 0 and k == (n - 1 + (m - 1)) // 2:
			continue
		g_ = list(g)
		zeros = sum((1 for x in g_ if x[1] == 0))
		ones = sum((1 for x in g_ if x[1] == 1))
		c += min(zeros, ones)
	print(c)
t = int(input())
for _ in range(t):
	process()


for ad in range(int(input())):
	(n, m) = list(map(int, input().split()))
	l = []
	for i in range(n):
		l.append(list(map(int, input().split())))
	ans = 0
	for ind_sum in range(0, (n + m - 1) // 2):
		c = 0
		zero = 0
		one = 0
		for i in range(n):
			j = ind_sum - i
			if 0 <= j < m and l[i][j] == 0:
				zero += 1
			elif 0 <= j < m and l[i][j] == 1:
				one += 1
			j = n + m - ind_sum - 2 - i
			if 0 <= j < m and l[i][j] == 0:
				zero += 1
			elif 0 <= j < m and l[i][j] == 1:
				one += 1
		c = min(zero, one)
		ans += c
	print(ans)


import sys, math
input = sys.stdin.readline

def getInts():
	return [int(s) for s in input().split()]

def getInt():
	return int(input())

def getStrs():
	return [s for s in input().split()]

def getStr():
	return input()

def listStr():
	return list(input())
import collections as col
import math

def solve():
	(N, M) = getInts()
	A = []
	for n in range(N):
		A.append(getInts())
	ans = 0
	for distance in range((N + M - 1) // 2):
		z = col.defaultdict(int)
		count = 0
		for x in range(min(distance + 1, N)):
			y = distance - x
			if y < 0 or y >= M:
				continue
			z[A[x][y]] += 1
			z[A[N - x - 1][M - y - 1]] += 1
			count += 2
		best = 0
		for key in z:
			best = max(best, z[key])
		ans += count - best
	return ans
for t in range(getInt()):
	print(solve())


def inp():
	return map(int, input().split())
for _ in range(int(input())):
	(n, m) = inp()
	a = [[-1 for j in range(m)] for i in range(m - 1)]
	for i in range(n):
		a.append(list(inp()))
	a += [[-1 for j in range(m)] for i in range(m - 1)]
	b = []
	for i in range(m - 1, len(a)):
		x = []
		for j in range(m):
			x.append(a[i - j][j])
		b.append(x)
	res = 0
	for i in range(len(b) // 2):
		x = b[i].count(0) + b[len(b) - i - 1].count(0)
		y = b[i].count(1) + b[len(b) - i - 1].count(1)
		res += min(x, y)
	print(res)


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	a = []
	for i in range(n):
		a.append(list(map(int, input().split())))
	x = (n + m) // 2
	ans = 0
	if (n + m - 1) % 2 == 0:
		x += 1
	for w in range(1, x):
		z = 0
		o = 0
		for i in range(w):
			for j in range(w):
				if w == i + j + 1 and i < n and (j < m):
					if a[i][j] == 0:
						z += 1
					else:
						o += 1
					if a[n - i - 1][m - j - 1] == 0:
						z += 1
					else:
						o += 1
		ans += min(o, z)
	print(ans)


from sys import stdin, stdout
t = int(stdin.readline().strip())
for _ in range(t):
	(n, m) = map(int, stdin.readline().split())
	M = []
	for _ in range(n):
		M.append(list(map(int, stdin.readline().split())))
	counts = {}
	for i in range(n):
		for j in range(m):
			k = i + j
			counts[k] = counts.get(k, 0) + M[i][j]
	ans = 0
	(s, e, c, d) = (0, m + n - 2, 2, 2 * min(m, n))
	while s < e:
		a = counts[s] + counts[e]
		ans += min(a, c - a)
		(s, e, c) = (s + 1, e - 1, min(d, c + 2))
	stdout.write('{}\n'.format(ans))


from sys import stdin
input = stdin.readline
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	a = []
	cnt = 0
	(cnt1, cnt2) = ([0] * (n + m), [0] * (n + m))
	nm = n + m - 2
	mid = (n + m - 1) // 2
	for x in range(n):
		a.append([int(y) for y in input().split()])
	for x in range(n):
		for y in range(m):
			if a[x][y] == 0:
				cnt1[x + y] += 1
			else:
				cnt2[x + y] += 1
	for x in range(mid):
		cnt += min(cnt1[x] + cnt1[nm - x], cnt2[x] + cnt2[nm - x])
	print(cnt)


def solution(A, n, m):
	cnt = 0
	for s in range((n + m - 1) // 2):
		diag1 = []
		diag2 = []
		for i in range(s + 1):
			j = s - i
			if i < n and j >= 0 and (j < m) and (i >= 0):
				diag1.append(A[i][j])
				diag2.append(A[-i - 1][-j - 1])
		k = len(diag1)
		cnt += min(sum(diag1) + sum(diag2), k - sum(diag1) + k - sum(diag2))
	return cnt
t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split(' '))
	A = []
	for _ in range(n):
		A.append(list(map(int, input().split(' '))))
	print(solution(A, n, m))


t = int(input())
for _ in range(t):
	(n, m) = list(map(int, input().strip().split()))
	list1 = []
	for _ in range(n):
		temp = list(map(int, input().strip().split()))
		list1.append(temp)
	ans = 0
	for k in range((n + m - 1) // 2):
		count0 = 0
		count1 = 0
		for i in range(n):
			for j in range(m):
				if i + j == k or i + j == n + m - 2 - k:
					if list1[i][j] == 0:
						count0 += 1
					else:
						count1 += 1
		ans += min(count0, count1)
	print(ans)


def pl(n, m):
	p = [[i + j + 1 for j in range(m)] for i in range(n)]
	for i in range(n):
		for j in range(m):
			if p[i][j] > (n + m) / 2:
				p[i][j] = n + m - p[i][j]
	return p

def b(n, m, M, p):
	b = 0
	for k in range(1, (n + m) // 2 + ((n + m) % 2 == 1)):
		c = []
		for i in range(n):
			for j in range(m):
				if p[i][j] == k:
					c += M[i][j]
		if c.count('1') >= c.count('0'):
			b += c.count('0')
		else:
			b += c.count('1')
	return b
t = int(input())
for i in range(t):
	(n, m) = map(int, input().split())
	p = pl(n, m)
	M = []
	for j in range(n):
		M += [input().split()]
	print(b(n, m, M, p))


t = int(input())
i = 0
while i < t:
	(n, m) = list(map(int, input().split()))
	j = 0
	l = []
	while j < n:
		ls = list(map(int, input().split()))
		l.append(ls)
		j += 1
	pathLen = n - 1 + m - 1 + 1
	j = 0
	summer = 0
	while j < pathLen // 2:
		ones = 0
		zeros = 0
		for k in range(n):
			for a in range(m):
				if a + k == j or a + k == n - 1 + m - 1 - j:
					if l[k][a] == 1:
						ones += 1
					else:
						zeros += 1
		summer += min(ones, zeros)
		j += 1
	print(summer)
	i += 1


t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	cost = 0
	a = []
	for i in range(n):
		c = list(map(int, input().split()))
		a.append(c)
	r = (n + m - 1) // 2
	if (r + 1) * 2 <= n + m - 1:
		r += 1
	for i in range(r):
		Q = i
		counter0 = 0
		counter1 = 0
		for j in range(Q + 1):
			if j >= m:
				continue
			if Q - j >= n:
				continue
			if a[Q - j][j] == 0:
				counter0 += 1
			else:
				counter1 += 1
		Q = n + m - 2 - i
		for j in range(Q + 1):
			if j >= m:
				continue
			if Q - j >= n:
				continue
			if a[Q - j][j] == 0:
				counter0 += 1
			else:
				counter1 += 1
		cost += min(counter0, counter1)
	print(cost)


t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	diagarr = [[0, 0] for i in range(n + m - 1)]
	for i in range(n):
		inp = list(map(int, input().split()))
		for j in range(m):
			if inp[j] == 1:
				diagarr[i + j][1] += 1
			else:
				diagarr[i + j][0] += 1
	op = 0
	for i in range((n + m - 1) // 2):
		if diagarr[i][0] + diagarr[n + m - 2 - i][0] >= diagarr[i][1] + diagarr[n + m - 2 - i][1]:
			op += diagarr[i][1] + diagarr[n + m - 2 - i][1]
		else:
			op += diagarr[i][0] + diagarr[n + m - 2 - i][0]
	print(op)


import sys
input = sys.stdin.readline
import math as ma
t = int(input())
for _ in range(t):
	(n, m) = list(map(int, input().split()))
	a = []
	for i in range(n):
		a.append(list(map(int, input().split())))
	c = 0
	d = []
	for i in range(n + m - 1):
		b = []
		for j in range(n):
			for k in range(m):
				if j + k == i:
					b.append(a[j][k])
		d.append(b)
	for i in range(len(d) // 2):
		e = d[i] + d[len(d) - 1 - i]
		c += min(e.count(1), e.count(0))
	print(c)


import sys
input = lambda : sys.stdin.readline().rstrip()
t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	a = []
	for _ in range(n):
		a.append(list(map(int, input().split())))
	ans = 0
	for i in range((n + m - 1) // 2):
		tmp = 0
		cnt = 0
		for j in range(max(0, i - m + 1), min(i + 1, n)):
			r = j
			c = i - j
			tmp += a[r][c]
			cnt += 1
		i = n + m - i - 2
		for j in range(max(0, i - m + 1), min(i + 1, n)):
			r = j
			c = i - j
			tmp += a[r][c]
			cnt += 1
		ans += min(tmp, cnt - tmp)
	print(ans)


from collections import deque
t = int(input())
for _ in range(t):
	(n, m) = [int(x) for x in input().split()]
	mat = [[int(x) for x in input().split()] for _ in range(n)]

	def valid(a):
		return 0 <= a[0] <= n - 1 and 0 <= a[1] <= m - 1
	totGrp = n + m - 1
	loop = totGrp // 2
	dtop = deque()
	dbot = deque()
	dtop.append((0, 0))
	dbot.append((n - 1, m - 1))
	ans = 0
	for _ in range(loop):
		zeros = 0
		ones = 0
		s1 = set()
		s2 = set()
		while dtop:
			(x1, y1) = dtop.popleft()
			(x2, y2) = dbot.popleft()
			if mat[x1][y1]:
				ones += 1
			else:
				zeros += 1
			if mat[x2][y2]:
				ones += 1
			else:
				zeros += 1
			tchoices = [(x1 + 1, y1), (x1, y1 + 1)]
			bchoices = [(x2 - 1, y2), (x2, y2 - 1)]
			for choice in tchoices:
				if valid(choice):
					s1.add(choice)
			for choice in bchoices:
				if valid(choice):
					s2.add(choice)
		ans += min(zeros, ones)
		ntop = deque([x for x in s1])
		nbot = deque([x for x in s2])
		dbot = nbot
		dtop = ntop
	print(ans)


import sys
input = sys.stdin.readline
Q = int(input())
Query = []
for _ in range(Q):
	(N, M) = map(int, input().split())
	Mat = [list(map(int, input().split())) for _ in range(N)]
	Query.append((N, M, Mat))
for (N, M, Mat) in Query:
	K = (N + M - 1) // 2
	ans = 0
	for k in range(K):
		dp1 = [0, 0]
		dp2 = [0, 0]
		for n in range(max(0, k + 1 - M), min(N, k + 1)):
			dp1[Mat[n][k - n]] += 1
			dp2[Mat[N - 1 - n][M - 1 - (k - n)]] += 1
		ans += min(dp1[1] + dp2[1], dp1[0] + dp2[0])
	print(ans)


import sys
from functools import lru_cache, cmp_to_key
from heapq import merge, heapify, heappop, heappush
from math import *
from collections import defaultdict as dd, deque, Counter as C
from itertools import combinations as comb, permutations as perm
from bisect import bisect_left as bl, bisect_right as br, bisect
from time import perf_counter
from fractions import Fraction
sys.setrecursionlimit(int(pow(10, 6)))
mod = int(pow(10, 9) + 7)
mod2 = 998244353

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

def out(*var, end='\n'):
	sys.stdout.write(' '.join(map(str, var)) + end)

def l():
	return list(sp())

def sl():
	return list(ssp())

def sp():
	return map(int, data().split())

def ssp():
	return map(str, data().split())

def l1d(n, val=0):
	return [val for i in range(n)]

def l2d(n, m, val=0):
	return [l1d(n, val) for j in range(m)]
for _ in range(l()[0]):
	(n, m) = l()
	A = [sl() for i in range(n)]
	B = []
	for i in range(n):
		for j in range(m):
			if (n + m - 1) % 2 and i + j == (n + m - 2) // 2:
				continue
			B.append([i + j, A[i][j]])
	C = []
	for i in range(n - 1, -1, -1):
		for j in range(m - 1, -1, -1):
			if (n + m - 1) % 2 and i + j == (n + m - 2) // 2:
				continue
			C.append([n + m - 2 - i - j, A[i][j]])
	B.sort()
	C.sort()
	k = 0
	i = 0
	while i < len(B):
		j = i
		c0 = c1 = b0 = b1 = 0
		while j < len(B) and B[i][0] == B[j][0]:
			if B[j][1] == '0':
				b0 += 1
			else:
				b1 += 1
			if C[j][1] == '0':
				c0 += 1
			else:
				c1 += 1
			j += 1
		k += min(b0 + c0, b1 + c1)
		i = j
	print(k // 2)


t = int(input())
for i in range(t):
	s = input().split()
	x = int(s[0])
	y = int(s[1])
	v = []
	s1 = [0] * (x + y - 1)
	k1 = [0] * (x + y - 1)
	for i in range(x):
		v.append([int(c) for c in input().split()])
	ans = 0
	for i in range(x + y - 1):
		s = 0
		k = 0
		for j in range(x + y - 1):
			if x - 1 >= i - j >= 0 and y - 1 >= j >= 0:
				k += 1
				s += v[i - j][j]
		k1[i] = k
		s1[i] = s
	for i in range(x + y - 1):
		if (x + y - 1) % 2 == 0 or ((x + y - 1) % 2 == 1 and i != (x + y) // 2 - 1):
			ans += min(k1[i] + k1[x + y - 2 - i] - s1[i] - s1[x + y - 2 - i], s1[i] + s1[x + y - 2 - i])
	print(ans // 2)


import sys
input = sys.stdin.readline
x = int(input())
for i in range(x):
	(a, b) = list(map(int, input().split()))
	mat = []
	mat_flip = []
	for j in range(a):
		temp = list(map(int, input().split()))
		mat.append(temp)
		mat_flip.append(temp[::-1])
	mat_flip = mat_flip[::-1]
	p = a + b - 3
	p = p // 2
	ans = 0
	for j in range(p):
		a1 = []
		a2 = []
		for e in range(j + 2):
			f = j + 1 - e
			if e >= 0 and e < a:
				if f >= 0 and f < b:
					a1.append(mat[e][f])
					a2.append(mat_flip[e][f])
		l = len(a1)
		m = min(sum(a1) + sum(a2), 2 * l - (sum(a1) + sum(a2)))
		ans += m
	if mat[0][0] != mat_flip[0][0]:
		ans += 1
	print(ans)


import math
N = int(input())
for iteration in range(N):
	dim = input().split(' ')
	row = int(dim[0])
	col = int(dim[1])
	total_diagonal = row + col - 1
	num_1 = [0 for i in range(total_diagonal)]
	num_0 = [0 for i in range(total_diagonal)]
	for r in range(row):
		rowdata = input().split(' ')
		for c in range(col):
			if rowdata[c] == '0':
				num_0[r + c] += 1
			else:
				num_1[r + c] += 1
	total_change = 0
	for i in range(math.floor(total_diagonal / 2)):
		total_1 = num_1[i] + num_1[-(i + 1)]
		total_0 = num_0[i] + num_0[-(i + 1)]
		total_change += min(total_1, total_0)
	print(total_change)


import math
for _ in range(int(input())):
	(a, b) = map(int, input().split())
	lis = []
	for i in range(a):
		lis.append(list(map(int, input().split())))
	count = []
	j = 1
	mid = math.ceil(b / 2)
	cost = []
	for i in range(a):
		x = [0, 0]
		j = 0
		while i >= 0 and j < b:
			if lis[i][j] == 1:
				x[1] += 1
			else:
				x[0] += 1
			i -= 1
			j += 1
		cost.append(x[:])
	for j in range(1, b):
		x = [0, 0]
		i = a - 1
		while i >= 0 and j < b:
			if lis[i][j] == 1:
				x[1] += 1
			else:
				x[0] += 1
			i -= 1
			j += 1
		cost.append(x[:])
	output = 0
	z = len(cost) - 1
	j = 0
	i = 0
	while i < len(cost) - 1 - j:
		if cost[i][0] + cost[len(cost) - 1 - j][0] > cost[i][1] + cost[len(cost) - 1 - j][1]:
			output += cost[i][1] + cost[len(cost) - 1 - j][1]
		else:
			output += cost[i][0] + cost[len(cost) - 1 - j][0]
		i += 1
		j += 1
	print(output)


t = int(input())
for i in range(t):
	(r, s) = map(int, input().split())
	a = [[0 for j in range(s)] for i in range(r)]
	for i in range(r):
		a[i] = list(map(int, input().split()))
	br = 0
	b = [[]] * (r + s - 1)
	for i in range(r):
		for j in range(s):
			b[i + j] = b[i + j] + [a[i][j]]
	for i in range(len(b) // 2):
		b[i] = b[i] + b[r + s - 2 - i]
		if 0 in b[i] and 1 in b[i]:
			br = br + min(b[i].count(0), b[i].count(1))
	print(br)


def count01(a, d):
	(n0, n1) = (0, 0)
	x = 0
	y = d - x
	while x < n and 0 <= y:
		if y < m:
			if a[x][y] == 0:
				n0 += 1
			else:
				n1 += 1
		x += 1
		y = d - x
	return (n0, n1)

def cnt(a):
	(n, m) = (len(a), len(a[0]))
	k = 0
	(dl, dr) = (0, n + m - 2)
	while dl < dr:
		(n0, n1) = count01(a, dl)
		(n02, n12) = count01(a, dr)
		n0 += n02
		n1 += n12
		k += min(n0, n1)
		dl += 1
		dr -= 1
	return k
t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	a = [[int(x) for x in input().split()] for _ in range(n)]
	print(cnt(a))


import sys
input = sys.stdin.readline
from collections import deque
t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	a = [list(map(int, input().split())) for i in range(n)]
	aa = [[0] * m for i in range(n)]
	arr = [[] for i in range(n + m - 1)]
	que = deque([[0, 0]])
	(x, y) = (0, 0)
	while len(que) > 0:
		xy = que.popleft()
		(x, y) = (xy[0], xy[1])
		num = aa[x][y]
		arr[num].append(a[x][y])
		if x + 1 < n:
			if aa[x + 1][y] == 0:
				que.append([x + 1, y])
				aa[x + 1][y] = aa[x][y] + 1
		if y + 1 < m:
			if aa[x][y + 1] == 0:
				que.append([x, y + 1])
				aa[x][y + 1] = aa[x][y] + 1
	ans = 0
	for i in range((n + m - 1) // 2):
		cnt = len(arr[i]) * 2
		left = sum(arr[i])
		right = sum(arr[n + m - 2 - i])
		s = left + right
		ans += min(s, cnt - s)
	print(ans)


from collections import defaultdict
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	A = []
	for i in range(n):
		k = list(map(int, input().split()))
		A.append(k)
	d = defaultdict(list)
	for i in range(n):
		for j in range(m):
			x = i + j
			y = n - i - 1 + m - j - 1
			if x != y:
				d[min(x, y)].append(A[i][j])
	ans = 0
	for i in d.keys():
		(o, z) = (0, 0)
		for j in d[i]:
			if j == 1:
				o += 1
			else:
				z += 1
		ans += min(z, o)
	print(ans)


import sys
pprint = lambda s: print(' '.join(map(str, s)))
input = lambda : sys.stdin.readline().strip()
ipnut = input

def f(a):
	o = a[0]
	all = a[1]
	z = all - o
	return min(o, z)
for i in range(int(input())):
	(n, m) = map(int, input().split())
	lvl = [[0, 0] for i in range(n + m - 1)]
	for i in range(n):
		a = list(map(int, input().split()))
		for j in range(m):
			lvl[i + j][0] += a[j]
			lvl[i + j][1] += 1
	ans = 0
	for i in range((n + m - 1) // 2):
		lvl[i][0] += lvl[-i - 1][0]
		lvl[i][1] += lvl[-i - 1][1]
		ans += f(lvl[i])
	print(ans)


import sys
import math

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

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

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

def SI():
	return list(sys.stdin.readline().strip())
t = II()
for q in range(t):
	(n, m) = MI()
	l = []
	for z in range(n):
		l.append(LI())
	d = []
	for i in range((n + m) // 2):
		d.append([])
	for i in range(n):
		for j in range(m):
			if i + j != n + m - 2 - i - j:
				d[min(i + j, n + m - 2 - i - j)].append(l[i][j])
	count = 0
	for i in d:
		c1 = 0
		c2 = 0
		for j in i:
			if j == 0:
				c1 += 1
			else:
				c2 += 1
		count += min(c1, c2)
	print(count)


a = int(input())
for i in range(a):
	(x, y) = map(int, input().split())
	(n, m) = (x, y)
	ans = []
	grp = [[0, 0] for i in range(n + m)]
	for i in range(x):
		z = list(map(int, input().split()))
		ans.append(z)
	for i in range(n):
		for j in range(m):
			if ans[i][j] == 0:
				grp[i + j][0] += 1
				grp[x - 1 + y - 1 - i - j][0] += 1
			if ans[i][j] == 1:
				k = i + j
				grp[k][1] += 1
				grp[n + m - 2 - k][1] += 1
	total = 0
	for i in range(n + m - 1):
		j = n + m - 2 - i
		if i <= j:
			continue
		else:
			total += min(grp[i][0] + grp[j][0], grp[i][1] + grp[j][1])
	print(total // 2)


t = int(input())
for i in range(t):
	(rows, columns) = [int(i) for i in input().split()]
	matrix = []
	for i in range(rows):
		inp = [int(i) for i in input().split()]
		matrix.append(inp)

	def numbersToChange(k):
		zeroes = 0
		ones = 0
		for x in range(min(k, columns - 1), max(k - rows + 1, 0) - 1, -1):
			y = k - x
			if matrix[y][x] == 0:
				zeroes += 1
			else:
				ones += 1
		return (ones, zeroes)
	s = 0
	diagonals = rows + columns - 1
	webech = int((diagonals - diagonals % 2) / 2)
	for k in range(webech):
		kum = numbersToChange(k)
		sum = numbersToChange(diagonals - k - 1)
		s += min(kum[0] + sum[0], kum[1] + sum[1])
	print(s)


a = int(input())
for _ in range(a):
	(b, c) = map(int, input().split())
	t = []
	k = []
	new = []
	hi = 0
	for _ in range(b):
		t.append(list(map(int, input().split())))
	for i in range(b + c - 1):
		l = max(0, i + 1 - c)
		r = min(i, c - 1)
		z = []
		while l < b and r >= 0:
			z.append(t[l][r])
			r -= 1
			l += 1
		k.append(z)
	zz = b + c - 1
	for i in range(zz // 2):
		helo = len(k[i])
		lis = [k[i][j] + k[zz - i - 1][j] for j in range(helo)]
		ab = sum(lis)
		tt = min(ab, 2 * helo - ab)
		hi += tt
	print(hi)


a = int(input())
for i in range(a):
	b = [int(x) for x in input().split()]
	xs = [1, 1]
	minside = min(b[0], b[1])
	xe = b
	line = []
	totalsum = 0
	for j in range(xe[0]):
		line.append([int(x) for x in input().split()])
	for k in range(1, b[0] + b[1] - 1):
		if xe[1] < xs[1] and xe[0] == xs[0] or (xs[0] > xe[0] and xe[1] == xs[1]) or xe == xs:
			break
		check = {}
		time = min(k, minside)
		for i in range(time):
			change = line[xe[0] - 1 - i][xe[1] - 1 + i]
			if change in check:
				check[change] += 1
			else:
				check[change] = 1
			change = line[xs[0] - 1 - i][xs[1] - 1 + i]
			if change in check:
				check[change] += 1
			else:
				check[change] = 1
		if 0 in check:
			if 1 in check:
				totalsum += min(check[0], check[1])
		if xe[1] != 1:
			xe[1] -= 1
		else:
			xe[0] -= 1
		if xs[0] != b[0]:
			xs[0] += 1
		else:
			xs[1] += 1
	check = {}
	print(totalsum)


import math
testcases = int(input())
for j in range(testcases):
	(n, m) = map(int, input().split())
	dict1 = {}
	for s in range(n):
		dict1[s] = list(map(int, input().split()))
	diags = (n + m - 1) // 2
	r1 = 0
	c1 = -1
	diffs = 0
	for s in range(diags):
		if c1 < m - 1:
			c1 += 1
		elif r1 < n - 1:
			r1 += 1
		diag1 = []
		cv = c1 + 0
		rv = r1 + 0
		while cv >= 0 and rv <= n - 1:
			diag1.append(dict1[rv][cv])
			cv -= 1
			rv += 1
		diag2 = []
		walks = c1 + r1
		if walks >= n - 1:
			cv2 = m - 1 - (walks - (n - 1))
			rv2 = 0
		else:
			cv2 = m - 1
			rv2 = n - 1 - walks
		while rv2 < n and cv2 >= 0:
			diag2.append(dict1[rv2][cv2])
			rv2 += 1
			cv2 -= 1
		oc1 = 0
		zc1 = 0
		oc2 = 0
		zc2 = 0
		for k in range(len(diag2)):
			if diag1[k] == 1:
				oc1 += 1
			else:
				zc1 += 1
			if diag2[k] == 1:
				oc2 += 1
			else:
				zc2 += 1
		diffs += min(2 * len(diag2) - oc1 - oc2, 2 * len(diag2) - zc1 - zc2)
	print(diffs)


def F(t, z, S, E, X):
	i = t[0]
	j = t[1]
	if z == 1:
		if i + 1 < n:
			S[i + 1, j] = X[i + 1][j]
		if j + 1 < m:
			S[i, j + 1] = X[i][j + 1]
	if z == -1:
		if i - 1 > -1:
			E[i - 1, j] = X[i - 1][j]
		if j - 1 > -1:
			E[i, j - 1] = X[i][j - 1]
T = int(input())
while T:
	(n, m) = map(int, input().split())
	X = []
	for i in range(n):
		X.append(list(map(int, input().split())))
	c = 0
	S = {}
	E = {}
	S[0, 0] = X[0][0]
	E[n - 1, m - 1] = X[n - 1][m - 1]
	L = S
	R = E
	while S != E and L != E:
		a = 0
		for s in S:
			a += S[s]
		b = 0
		for e in E:
			b += E[e]
		c = c + min(a + b, len(S) + len(E) - a - b)
		P = {}
		Q = {}
		for s in S:
			F(s, 1, P, Q, X)
		for e in E:
			F(e, -1, P, Q, X)
		L = S
		R = E
		S = P
		E = Q
	print(c)
	T = T - 1


t = int(input())
for i in range(t):
	(n, m) = list(map(int, input().split(' ')))
	board = [0] * n
	for j in range(n):
		row = list(map(int, input().split(' ')))
		board[j] = row
	zeros = [0] * (m + n - 1)
	ones = [0] * (m + n - 1)
	for row in range(n):
		for col in range(m):
			if board[row][col] == 0:
				zeros[row + col] += 1
			else:
				ones[row + col] += 1
	changes = 0
	for step in range((m + n - 1) // 2):
		current_zeros = zeros[step] + zeros[m + n - 2 - step]
		current_ones = ones[step] + ones[m + n - 2 - step]
		changes += min(current_ones, current_zeros)
	print(changes)


import sys
import io
import math
import collections
import decimal
import itertools
import bisect
import heapq

def input():
	return sys.stdin.readline()[:-1]
INF = 10 ** 10

def solve(N, M, A):
	R = N + M - 1
	Counter = [[0, 0] for _ in range(R)]
	for i in range(N):
		for j in range(M):
			Counter[i + j][A[i][j]] += 1
	res = 0
	for i in range(R // 2):
		res += min(Counter[i][0] + Counter[R - 1 - i][0], Counter[i][1] + Counter[R - 1 - i][1])
	return res
T0 = int(input())
for _ in range(T0):
	(N, M) = map(int, input().split())
	A = [list(map(int, input().split())) for _ in range(N)]
	print(solve(N, M, A))


t = int(input())
for i in range(t):
	(n, m) = map(int, input().split())
	p = [[0, 0] for j in range((n + m - 1) // 2)]
	for j in range(n):
		a = [int(i) for i in input().split()]
		for x in range(m):
			if (n + m - 1) % 2 == 1:
				if j + x > (n + m - 1) // 2:
					if a[x] == 0:
						p[n - 1 + m - 1 - (j + x)][0] += 1
					else:
						p[n - 1 + m - 1 - (j + x)][1] += 1
				elif j + x < (n + m - 1) // 2:
					if a[x] == 0:
						p[j + x][0] += 1
					else:
						p[j + x][1] += 1
				else:
					pass
			elif a[x] == 1:
				p[min(n + m - 2 - (j + x), j + x)][1] += 1
			else:
				p[min(n + m - 2 - (j + x), j + x)][0] += 1
	ans = 0
	for i in p:
		ans += min(i[0], i[1])
	print(ans)


from sys import stdin, stdout
for t in range(int(stdin.readline())):
	(n, m) = map(int, stdin.readline().split())
	a = [0] * (n + m - 1)
	b = [0] * (n + m - 1)
	for i in range(n):
		c = 0
		for j in map(int, stdin.readline().strip().split()):
			if j == 0:
				a[i + c] += 1
			else:
				b[i + c] += 1
			c += 1
	cost = 0
	u = (n + m) // 2
	if (n + m) % 2 == 0:
		u = (n + m) // 2 - 1
	for i in range(u):
		cost += min(a[i] + a[n + m - 2 - i], b[i] + b[n + m - 2 - i])
	print(cost)


def stripe(k):
	for i in range(k + 1):
		if i < n and k - i < m:
			yield a[i][k - i]
			yield a[n - 1 - i][m - 1 - (k - i)]

def solve(n, m, a):
	ans = 0
	for k in range((n + m - 1) // 2):
		vals = list(stripe(k))
		ans += min(len(vals) - sum(vals), sum(vals))
	return ans
t = int(input().strip())
for _ in range(t):
	(n, m) = list(map(int, input().strip().split()))
	a = []
	for _ in range(n):
		a.append(list(map(int, input().strip().split())))
	print(solve(n, m, a))


import os
import sys
from io import BytesIO, IOBase
profile = 0
pypy = 1

def iin():
	return int(input())

def lin():
	return list(map(int, input().split()))

def BFS(adj, c1):
	s = (0, 0)
	parent = {s: None}
	u = [s]
	lv = [[s]]
	while u:
		temp = []
		for v in u:
			for v1 in adj[v]:
				if v1 not in parent:
					parent[v1] = v
					temp.append(v1)
		u = temp
		if u:
			lv.append(u)
	ans = 0
	l1 = []
	for i in lv:
		ch = [0, 0]
		for (j, k) in i:
			ch[c1[j][k]] += 1
		l1.append(ch)
	n = len(l1)
	for i in range(n // 2):
		ch = l1[-i - 1]
		ch1 = l1[i]
		ch[0] += ch1[0]
		ch[1] += ch1[1]
		ans += min(ch)
	return ans

def main():
	T = iin()
	while T:
		T -= 1
		(n, m) = lin()
		c1 = [lin() for i in range(n)]

		def find(i, j):
			x = []
			if i < n - 1:
				x.append((i + 1, j))
			if j < m - 1:
				x.append((i, j + 1))
			return x
		adj = {(i, j): find(i, j) for i in range(n) for j in range(m)}
		sol = BFS(adj, c1)
		print(sol)
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')
if pypy:
	(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
	input = lambda : sys.stdin.readline().rstrip('\r\n')
if profile:
	import cProfile
	cProfile.run('main()')
else:
	main()


import sys
from collections import defaultdict as dd
from collections import deque
from fractions import Fraction as f

def eprint(*args):
	print(*args, file=sys.stderr)
zz = 1
from math import *
import copy
if zz:
	input = sys.stdin.readline
else:
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('all.txt', 'w')

def li():
	return [int(x) for x in input().split()]

def fi():
	return int(input())

def si():
	return list(input().rstrip())

def mi():
	return map(int, input().split())

def gh():
	sys.stdout.flush()

def bo(i):
	return ord(i) - ord('a')
from copy import *
from bisect import *
from itertools import permutations
t = int(input())
while t > 0:
	t -= 1
	(n, m) = mi()
	a = []
	d = [[0, 0] for i in range(n + m + 10)]
	for i in range(n):
		p = li()
		a.append(p)
	for i in range(n):
		for j in range(m):
			d[i + j][a[i][j]] += 1
	c = 0
	p = n + m - 2
	for i in range(p // 2 + 1):
		if p - i < 0 or i == p - i:
			continue
		c += min(d[i][1] + d[p - i][1], d[i][0] + d[p - i][0])
	print(c)


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	l = [list(map(int, input().split())) for i in range(n)]
	q = [(0, 0), (n - 1, m - 1)]
	v = [(0, 0), (n - 1, m - 1)]
	c = 0
	c_ = 0
	while q and c < (n + m - 1) // 2:
		ne = []
		out = []
		(c0, c1) = (0, 0)
		for (i, j) in q:
			out.append((i, j))
			c0 += int(not l[i][j])
			c1 += l[i][j]
			if i > 0 and (i - 1, j) not in v and ((i - 1, j) not in ne):
				ne.append((i - 1, j))
			if i < n - 1 and (i + 1, j) not in v and ((i + 1, j) not in ne):
				ne.append((i + 1, j))
			if j > 0 and (i, j - 1) not in v and ((i, j - 1) not in ne):
				ne.append((i, j - 1))
			if j < m - 1 and (i, j + 1) not in v and ((i, j + 1) not in ne):
				ne.append((i, j + 1))
		for i in out:
			q.remove(i)
		q += ne
		v += ne
		c += 1
		c_ += min(c0, c1)
	print(c_)


from sys import stdin, stdout
import math

def main():
	t = int(stdin.readline())
	ans = [0 for i in range(t)]
	for q in range(t):
		(n, m) = map(int, stdin.readline().split())
		ways = []
		groups = [[] for i in range(n + m - 1)]
		for i in range(n):
			x = [int(x) for x in stdin.readline().split()]
			ways.append(x)
		for i in range(n):
			for j in range(m):
				groups[i + j].append(ways[i][j])
		ans[q] += groups[0][0] != groups[-1][-1]
		for k in range(1, len(groups) // 2):
			if n + m % 2 == 1 or i + j != (n + m - 1) // 2:
				cost = min(groups[k].count(0) + groups[n + m - 2 - k].count(0), groups[k].count(1) + groups[n + m - 2 - k].count(1))
				ans[q] += cost
			else:
				for i in range(len(groups[k]) // 2):
					if groups[k] != groups[len(groups[k]) - k - 1]:
						ans[q] += 1
	for i in range(t):
		print(ans[i])
main()


from sys import stdin, stdout

def palindromic_paths(n, m, a):
	q1 = [[0, 0]]
	q2 = [[n - 1, m - 1]]
	dirs = [[1, 0], [-1, 0], [0, 1], [0, -1]]
	res = 0
	step = 0
	vis = [[False for j in range(m)] for i in range(n)]
	vis[0][0] = True
	vis[n - 1][m - 1] = True
	while step < (m + n - 1) // 2:
		qcnt = len(q1)
		c0 = 0
		c1 = 0
		for i in range(qcnt):
			d1 = q1.pop(0)
			d2 = q2.pop(0)
			if a[d1[0]][d1[1]] == 1:
				c1 += 1
			else:
				c0 += 1
			if a[d2[0]][d2[1]] == 1:
				c1 += 1
			else:
				c0 += 1
			for dir in dirs:
				ni = d1[0] + dir[0]
				nj = d1[1] + dir[1]
				if ni < 0 or ni >= n or nj < 0 or (nj >= m) or vis[ni][nj]:
					continue
				vis[ni][nj] = True
				q1.append([ni, nj])
			for dir in dirs:
				ni = d2[0] + dir[0]
				nj = d2[1] + dir[1]
				if ni < 0 or ni >= n or nj < 0 or (nj >= m) or vis[ni][nj]:
					continue
				vis[ni][nj] = True
				q2.append([ni, nj])
		res += min(c1, c0)
		step += 1
	return res
t = int(stdin.readline())
for i in range(t):
	(n, m) = list(map(int, stdin.readline().split()))
	a = []
	for j in range(n):
		a.append(list(map(int, stdin.readline().split())))
	stdout.write(str(palindromic_paths(n, m, a)) + '\n')


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	a = []
	for i in range(n):
		a.append(list(map(int, input().split())))
	d = [[0, 0] for i in range(70)]
	for i in range(n):
		for j in range(m):
			if i + j != m + n - 2 - i - j:
				d[min(i + j, m + n - 2 - i - j)][a[i][j]] += 1
	ans = 0
	for i in range(70):
		ans += min(d[i][0], d[i][1])
	print(ans)


def merge(a, b):
	x = a.count('0') + b.count('0')
	y = len(a) + len(b) - x
	return min(x, y)
t = int(input())
for i in range(t):
	(n, m) = map(int, input().split())
	row = []
	for j in range(n):
		s = input()
		s = s.replace(' ', '')
		row.append(s)
	matrix = ['' for h in range(n + m - 1)]
	for x in range(m):
		for y in range(n):
			matrix[x + y] += row[y][x]
	count = 0
	for g in range((m + n - 1) // 2):
		count += merge(matrix[g], matrix[-1 - g])
	print(count)


from fractions import Fraction
import sys
import bisect
import heapq
from math import *
from collections import Counter as counter
from itertools import combinations as comb
from itertools import permutations as permutate
from bisect import bisect_left as bl
from bisect import bisect_right as br
from bisect import bisect
mod = 1000000007

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

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 graph(vertex):
	return [[] for i in range(0, vertex + 1)]

def zerolist(n):
	return [0] * n

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

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

def printlist(a):
	for p in range(0, len(a)):
		out(str(a[p]) + ' ')

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

def power(a, b):
	ans = 1
	while b > 0:
		if b % 2 == 1:
			ans *= a
		a *= a
		b //= 2
	return ans

def solve():
	(n, m) = sep()
	grid = []
	length = m - 1 + (n - 1) + 1
	for i in range(0, n):
		temp = lis()
		grid.append(temp)
	dist = [[] for i in range(length // 2)]
	if length % 2 == 0:
		chck = False
	else:
		chck = True
	for i in range(0, n):
		for j in range(0, m):
			if i + j >= length // 2:
				if n - 1 - i + (m - 1 - j) >= length // 2:
					continue
				else:
					dist[n - 1 - i + (m - 1 - j)].append(grid[i][j])
			else:
				dist[i + j].append(grid[i][j])
	ans = 0
	for i in range(0, len(dist)):
		cnt0 = 0
		cnt1 = 0
		for j in range(0, len(dist[i])):
			if dist[i][j] == 0:
				cnt0 += 1
			else:
				cnt1 += 1
		ans += min(cnt0, cnt1)
	print(ans)
testcase(int(inp()))


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	matrix = []
	for i in range(n):
		matrix.append(list(map(int, input().split())))
	ans = 0
	for step in range(0, (n + m - 3) // 2 + 1):
		zeroes = 0
		ones = 0
		for i in range(n):
			if i > step:
				break
			if step - i > m - 1:
				continue
			if matrix[i][step - i] == 0:
				zeroes += 1
			else:
				ones += 1
			if matrix[n - 1 - i][m - 1 - step + i] == 0:
				zeroes += 1
			else:
				ones += 1
		if zeroes < ones:
			ans += zeroes
		else:
			ans += ones
	print(ans)


def as_list():
	return list(map(int, input().split()))

def solve():
	matrix = []
	[n, m] = as_list()
	for i in range(n):
		matrix.append(as_list())
	path_length = (m + n - 1) // 2
	classes = []
	for _ in range(path_length):
		classes.append([0, 0])
	for r in range(n):
		for c in range(m):
			_class = r + c
			if _class >= path_length:
				_class = n + m - 2 - _class
			if _class >= path_length:
				continue
			classes[_class][matrix[r][c]] += 1
	cost = 0
	for i in range(path_length):
		cost += min(classes[i][0], classes[i][1])
	return cost
[tests] = as_list()
for _ in range(tests):
	print(solve())


import sys
input = sys.stdin.readline

def ceil(x):
	if x != int(x):
		x = int(x) + 1
	return x

def factorial(x, m):
	val = 1
	while x > 0:
		val = val * x % m
		x -= 1
	return val

def swaparr(arr, a, b):
	temp = arr[a]
	arr[a] = arr[b]
	arr[b] = temp

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

def nCr(n, k):
	if k > n - k:
		k = n - k
	res = 1
	for i in range(k):
		res = res * (n - i)
		res = res / (i + 1)
	return int(res)

def upper_bound(a, x, lo=0, hi=None):
	if hi == None:
		hi = len(a)
	while lo < hi:
		mid = (lo + hi) // 2
		if a[mid] < x:
			lo = mid + 1
		else:
			hi = mid
	return lo

def primefs(n):
	primes = {}
	while n % 2 == 0 and n > 0:
		primes[2] = primes.get(2, 0) + 1
		n = n // 2
	for i in range(3, int(n ** 0.5) + 2, 2):
		while n % i == 0 and n > 0:
			primes[i] = primes.get(i, 0) + 1
			n = n // i
	if n > 2:
		primes[n] = primes.get(n, 0) + 1
	return primes

def power(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

def swap(a, b):
	temp = a
	a = b
	b = temp
	return (a, b)

def find(x, link):
	p = x
	while p != link[p]:
		p = link[p]
	while x != p:
		nex = link[x]
		link[x] = p
		x = nex
	return p

def union(x, y, link, size):
	x = find(x, link)
	y = find(y, link)
	if size[x] < size[y]:
		(x, y) = swap(x, y)
	if x != y:
		size[x] += size[y]
		link[y] = x

def sieve(n):
	prime = [True for i in range(n + 1)]
	p = 2
	while p * p <= n:
		if prime[p] == True:
			for i in range(p * p, n + 1, p):
				prime[i] = False
		p += 1
	return prime
MAXN = int(100000.0 + 5)

def spf_sieve():
	spf[1] = 1
	for i in range(2, MAXN):
		spf[i] = i
	for i in range(4, MAXN, 2):
		spf[i] = 2
	for i in range(3, ceil(MAXN ** 0.5), 2):
		if spf[i] == i:
			for j in range(i * i, MAXN, i):
				if spf[j] == j:
					spf[j] = i

def factoriazation(x):
	ret = {}
	while x != 1:
		ret[spf[x]] = ret.get(spf[x], 0) + 1
		x = x // spf[x]
	return ret

def int_array():
	return list(map(int, input().strip().split()))

def float_array():
	return list(map(float, input().strip().split()))

def str_array():
	return input().strip().split()
MOD = int(1000000000.0) + 7
CMOD = 998244353
INF = float('inf')
NINF = -float('inf')

def solve():
	(n, m) = map(int, input().split())
	a = []
	for i in range(n):
		a.append(list(map(int, input().split())))
	d = {}
	for i in range(n):
		for j in range(m):
			val1 = i + j
			val2 = n - i - 1 + m - j - 1
			if val1 == val2:
				continue
			val = min(val1, val2)
			if d.get(val) == None:
				d[val] = [a[i][j]]
			else:
				d[val].append(a[i][j])
	ans = 0
	for x in d.values():
		ones = x.count(1)
		zeroes = x.count(0)
		ans += min(ones, zeroes)
	print(ans)
for _ in range(int(input())):
	solve()


import math, sys
from collections import defaultdict, deque
import bisect as bi

def yes():
	print('YES')

def no():
	print('NO')

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

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

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

def dict(a):
	d = {}
	for x in a:
		if d.get(x, -1) != -1:
			d[x] += 1
		else:
			d[x] = 1
	return d

def find_gt(a, x):
	i = bi.bisect_left(a, x)
	if i != len(a):
		return i
	else:
		return -1

def main():
	try:
		(n, m) = In()
		l = [list(In()) for i in range(n)]
		cnt = [[0, 0] for i in range(n + m - 1)]
		for i in range(n):
			for j in range(m):
				le = min(i + j, n - i - 1 + m - j - 1)
				if l[i][j] == 1:
					cnt[le][1] += 1
				else:
					cnt[le][0] += 1
		ans = 0
		for i in range((n + m - 1) // 2):
			ans += min(cnt[i])
		print(ans)
	except:
		pass
M = 998244353
P = 1000000007
for _ in range(I()):
	main()


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')
from math import gcd, ceil

def pre(s):
	n = len(s)
	pi = [0] * n
	for i in range(1, n):
		j = pi[i - 1]
		while j and s[i] != s[j]:
			j = pi[j - 1]
		if s[i] == s[j]:
			j += 1
		pi[i] = j
	return pi

def prod(a):
	ans = 1
	for each in a:
		ans = ans * each
	return ans

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

def binary(x, length=16):
	y = bin(x)[2:]
	return y if len(y) >= length else '0' * (length - len(y)) + y

def getOverlap(a, b):
	return max(0, min(a[1], b[1]) - max(a[0], b[0]) + 1)

def isPalin(str):
	l = len(str) // 2
	for i in range(l):
		if str[i] != str[len(str) - i - 1]:
			return False
	return True

class F:
	ans = 0

def palindromicPath(str, a, i, j, m, n):
	if j < m - 1 or i < n - 1:
		if i < n - 1:
			palindromicPath(str + a[i][j], a, i + 1, j, m, n)
		if j < m - 1:
			palindromicPath(str + a[i][j], a, i, j + 1, m, n)
	else:
		str = str + a[n - 1][m - 1]
		if str == str[::-1]:
			F.ans += 1
for _ in range(int(input()) if True else 1):
	(n, m) = map(int, input().split())
	a = []
	for __ in range(n):
		a += [list(map(int, input().split()))]
	x = [0] * (m + n - 1)
	y = list(x)
	for i in range(n):
		for j in range(m):
			if not a[i][j]:
				x[i + j] += 1
			else:
				y[i + j] += 1
	mid = (m + n - 2) // 2
	ans = 0
	for i in range(mid):
		ans += min(x[i] + x[n + m - 2 - i], y[i] + y[n + m - 2 - i])
	if (n + m) % 2:
		ans += min(x[mid] + x[n + m - 2 - mid], y[mid] + y[n + m - 2 - mid])
	print(ans)


import sys
import math
input = sys.stdin.readline
t = int(input())
for cs in range(t):
	(n, m) = map(int, input().split())
	a = [[] for _ in range(n)]
	for i in range(n):
		a[i] = [int(x) for x in input().split()]
	can = [[] for _ in range(n + m)]
	for i in range(n):
		for j in range(m):
			d1 = i + j
			d2 = abs(n - 1 - i) + abs(m - 1 - j)
			if d1 < d2:
				can[d1].append(a[i][j])
			elif d1 != d2:
				can[d2].append(a[i][j])
	ans = 0
	for i in can:
		ans = ans + min(sum(i), len(i) - sum(i))
	print(ans)


t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	x1 = [0] * (m + n - 1)
	x2 = [0] * (m + n - 1)
	l = []
	for i in range(n):
		l1 = list(map(int, input().split()))
		l.append(l1)
	for i in range(n):
		for j in range(m):
			if l[i][j] == 0:
				x1[i + j] += 1
			else:
				x2[i + j] += 1
	mid = (m + n - 2) // 2
	ans = 0
	for i in range(mid + 1):
		if i == mid and (m + n) % 2 == 0:
			continue
		else:
			ans += min(x1[i] + x1[n + m - 2 - i], x2[i] + x2[n + m - 2 - i])
	print(ans)


import math
t = int(input())
for i in range(t):
	(n, m) = map(int, input().split())
	ma = []
	for j in range(n):
		l = list(map(int, input().split()))
		ma.append(l)
	re = {}
	for i in range((n + m) // 2 - (n + m + 1) % 2):
		re[i] = [0, 0]
	for i in range(n):
		for j in range(m):
			if i + j in re:
				re[i + j][ma[i][j]] += 1
			elif n + m - 2 - (i + j) in re:
				re[n + m - 2 - (i + j)][ma[i][j]] += 1
	ans = 0
	for c in re:
		ans += min(re[c])
	print(ans)


import sys
input = sys.stdin.readline
import math

def inp():
	return int(input())

def inlt():
	return list(map(int, input().split()))

def insr():
	s = input().strip()
	return list(s[:len(s)])

def invr():
	return map(int, input().strip().split())

def from_file(f):
	return f.readline

def solution(n, m, A):
	L = n + m - 1
	T = []
	for l in range(1, L + 1):
		c = [0, 0]
		for i in range(min(l, n)):
			j = l - i - 1
			if j >= m:
				continue
			c[A[i][j]] += 1
		T.append(c)
	res = 0
	for l in range(1, L // 2 + 1):
		res += min(T[l - 1][0] + T[m + n - l - 1][0], T[l - 1][1] + T[n + m - l - 1][1])
	return res
t = inp()
for _ in range(t):
	(n, m) = invr()
	A = []
	for _ in range(n):
		A.append(inlt())
	print(solution(n, m, A))


from collections import defaultdict

def read_list():
	return list(map(int, input().split(' ')))
N = int(input())
for _ in range(N):
	dic = defaultdict(lambda : [0, 0])
	(n, m) = read_list()
	for i in range(n):
		num = read_list()
		for j in range(m):
			if num[j] == 1:
				dic[i + j][1] += 1
			else:
				dic[i + j][0] += 1
	res = 0
	for k in range(m + n - 1 >> 1):
		res += min(dic[k][0] + dic[m + n - 2 - k][0], dic[k][1] + dic[m + n - 2 - k][1])
	print(res)


from sys import stdin, stdout
from math import floor, gcd, fabs, factorial, fmod, sqrt, inf, log
from collections import defaultdict as dd, deque
from heapq import merge, heapify, heappop, heappush, nsmallest
from bisect import bisect_left as bl, bisect_right as br, bisect
mod = pow(10, 9) + 7
mod2 = 998244353

def inp():
	return stdin.readline().strip()

def out(var, end='\n'):
	stdout.write(str(var) + '\n')

def outa(*var, end='\n'):
	stdout.write(' '.join(map(str, var)) + end)

def lmp():
	return list(mp())

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

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

def l1d(n, val=0):
	return [val for i in range(n)]

def l2d(n, m, val=0):
	return [l1d(m, val) for j in range(n)]

def remadd(x, y):
	return 1 if x % y else 0

def ceil(a, b):
	return (a + b - 1) // b

def isprime(x):
	if x <= 1:
		return False
	if x in (2, 3):
		return True
	if x % 2 == 0:
		return False
	for i in range(3, int(sqrt(x)) + 1, 2):
		if x % i == 0:
			return False
	return True
for _ in range(int(inp())):
	(n, m) = mp()
	ml = []
	for i in range(n):
		l = lmp()
		ml.append(l)
	t = n + m - 1
	nl = [[0, 0] for i in range(t // 2 + t % 2)]
	for i in range(n):
		for j in range(m):
			nl[min(i + j, t - 1 - (i + j))][ml[i][j]] += 1
	ans = 0
	for i in range(t // 2):
		ans += min(nl[i])
	print(ans)


t = int(input())
for i in range(t):
	(n, m) = map(int, input().split())
	matrix = []
	for j in range(n):
		matrix.append(input().split())
	count = [[0 for j in range(2)] for k in range(n + m)]
	for j in range(n):
		for k in range(m):
			count[j + k][int(matrix[j][k])] += 1
	ans = 0
	for j in range(n + m - 1):
		temp = n + m - 2 - j
		if j <= temp:
			continue
		ans += min(count[j][0] + count[temp][0], count[j][1] + count[temp][1])
	print(ans)


def inp():
	return int(input())

def inlt():
	return list(map(int, input().split()))

def insr():
	s = input()
	return list(s[:len(s)])

def invr():
	return map(int, input().split())
entries = inp()
for i in range(entries):
	l = inlt()
	n = l[0]
	m = l[1]
	mat = []
	for j in range(n):
		mat.append(inlt())
	dist = []
	d = {}
	for i in range(n):
		dist.append([])
		for j in range(m):
			dist[i].append(min(i + j, n - i - 1 + m - j - 1))
			if dist[i][j] not in d:
				d[dist[i][j]] = []
				d[dist[i][j]].append([i, j])
			else:
				d[dist[i][j]].append([i, j])
	threshold = (n + m - 1) // 2
	res = 0
	for x in d:
		if x < threshold:
			l = d[x]
			val = 0
			for y in l:
				val += mat[y[0]][y[1]]
			if val >= len(l) // 2:
				res += len(l) - val
			else:
				res += val
	print(res)


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	mat = []
	l = n + m - 1
	for i in range(n):
		mat.append(list(map(int, input().split())))
	lim = l // 2
	f11 = [0 for i in range(n + m - 1)]
	f10 = [0 for i in range(n + m - 1)]
	for i in range(n):
		for j in range(m):
			if mat[i][j]:
				f11[i + j] += 1
			else:
				f10[i + j] += 1
	ans = 0
	for i in range(lim):
		ans += min(f11[i] + f11[l - i - 1], f10[i] + f10[l - i - 1])
	print(ans)


def gns():
	return list(map(int, input().split()))
t = int(input())
for i in range(t):
	(n, m) = gns()
	nm = []
	for i in range(n):
		nm.append(gns())
	d = {}
	ans = 0
	for i in range(n):
		for j in range(m):
			dis1 = n - 1 - i + (m - 1 - j)
			dis2 = i + j
			dis = min(dis1, dis2)
			if dis not in d:
				d[dis] = [0, 0]
			d[dis][nm[i][j]] += 1
	if (n + m) % 2 == 0:
		mid = (m + n - 2) // 2
		d[mid] = [0, 0]
	for i in d:
		ans += min(d[i])
	print(ans)


for _ in range(int(input())):
	(n, m) = [int(c) for c in input().split()]
	arr = []
	for i in range(n):
		a = [int(c) for c in input().split()]
		arr.append(a)
	count = [[0 for i in range(2)] for j in range(n + m)]
	for i in range(n):
		for j in range(m):
			count[i + j][arr[i][j]] += 1
	ans = 0
	for i in range(n + m - 2 + 1):
		j = n + m - 2 - i
		if i <= j:
			continue
		ans += min(count[i][0] + count[j][0], count[i][1] + count[j][1])
	print(ans)


testes = int(input())
for t in range(testes):
	(n, m) = input().split()
	n = int(n)
	m = int(m)
	soma = m + n - 2
	A = []
	v = []
	for i in range(n):
		A.append([])
		for j in range(m):
			A[i].append(0)
	for i in range(m + n):
		v.append([])
		for j in range(2):
			v[i].append(0)
	for i in range(n):
		aux = input().split()
		for j in range(m):
			A[i][j] = int(aux[j])
			if i + j != soma - i - j:
				aux1 = min(i + j, soma - i - j)
				v[aux1][int(A[i][j])] = v[aux1][int(A[i][j])] + 1
	minimo = 0
	for i in v:
		minimo = minimo + min(i[0], i[1])
	print(minimo)


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	d = {}
	for i in range(n):
		l = list(map(int, input().split()))
		for j in range(m):
			if i + j not in d:
				d[i + j] = [l[j]]
			else:
				d[i + j].append(l[j])
	dist = n + m - 2
	ans = 0
	for i in range(dist):
		if dist - i > i:
			t1 = d[dist - i].count(1) + d[i].count(1)
			t0 = d[dist - i].count(0) + d[i].count(0)
			ans += min(t1, t0)
		else:
			break
	print(ans)


def main():
	(n, m) = map(int, input().split())
	arr0 = [0 for _ in range(n + m)]
	arr1 = [0 for _ in range(n + m)]
	for i in range(n):
		a = list(map(int, input().split()))
		for j in range(m):
			if a[j] == 0:
				arr0[i + j] += 1
			else:
				arr1[i + j] += 1
	ans = 0
	if (n + m - 1) % 2 != 0:
		length = (n + m - 2) // 2
	else:
		length = (n + m - 1) // 2
	for i in range(length):
		ans += min(arr0[i] + arr0[n + m - 2 - i], arr1[i] + arr1[n + m - 2 - i])
	print(ans)
	return

def test():
	t = int(input())
	while t:
		main()
		t -= 1
test()


import sys
read = sys.stdin.buffer.readline
cin = lambda : int(read())
mi = lambda : map(int, read().split())
for _ in range(cin()):
	(n, m) = mi()
	a = []
	for i in range(n):
		a.append(list(mi()))
	vis = [[0 for i in range(m)] for j in range(n)]
	st = [[0, 0]]
	ans = 0
	vis[0][0] = 1
	b = []
	while st:
		(nz, no) = (0, 0)
		tmp = []
		for el in st:
			(i, j) = (el[0], el[1])
			if a[el[0]][el[1]] == 1:
				no += 1
			else:
				nz += 1
			if i + 1 < n and vis[i + 1][j] == 0:
				vis[i + 1][j] = 1
				tmp.append([i + 1, j])
			if j + 1 < m and vis[i][j + 1] == 0:
				vis[i][j + 1] = 1
				tmp.append([i, j + 1])
		st = tmp
		b.append([nz, no])
	ans = 0
	n = len(b)
	for i in range(len(b) // 2):
		ans += min(b[i][0] + b[n - i - 1][0], b[i][1] + b[n - i - 1][1])
	print(ans)


from collections import Counter

def cons(arr):
	l = len(arr)
	w = len(arr[0])
	temp1 = []
	for x in range(0, len(arr)):
		i = x
		j = 0
		temp = []
		while j < w and i >= 0:
			temp.append(arr[i][j])
			j += 1
			i -= 1
		temp1.append(temp)
	for x in range(1, w):
		i = x
		j = l - 1
		temp = []
		while i < w and j >= 0:
			temp.append(arr[j][i])
			j -= 1
			i += 1
		temp1.append(temp)
	return temp1
for i in range(int(input())):
	(a, b) = [int(i) for i in input().split()]
	arr = []
	for i in range(a):
		arr.append([int(i) for i in input().split()])
	temp = cons(arr)
	ans = 0
	for i in range(len(temp) // 2):
		cnt = Counter(temp[i] + temp[len(temp) - i - 1])
		a = cnt.get(1, 0)
		b = cnt.get(0, 0)
		if a > b:
			ans += b
		else:
			ans += a
	print(ans)


def solve():
	(n, m) = map(int, input().split())
	a = [list(map(int, input().split())) for i in range(n)]
	cnt = 0
	for i in range((n + m - 1) // 2):
		c0 = 0
		c1 = 0
		ok = True
		for j in range(0, min(i + 1, m, n)):
			if i < n:
				if a[i - j][0 + j]:
					c1 += 1
				else:
					c0 += 1
				if m - 1 - i + j >= 0 and ok:
					if a[n - 1 - j][m - 1 - i + j]:
						c1 += 1
					else:
						c0 += 1
				else:
					ok = False
					ii = n - 1 - (i - m + 1) + 1
					if a[ii - j - 1][j]:
						c1 += 1
					else:
						c0 += 1
			else:
				ii = i - n + 1
				if a[n - 1 - j][ii + j]:
					c1 += 1
				else:
					c0 += 1
				if a[n - 1 - j][m - i - 1 + j]:
					c1 += 1
				else:
					c0 += 1
		cnt += min(c1, c0)
	print(cnt)
t = int(input())
for _ in range(t):
	solve()


t = int(input())
for _ in range(t):
	(n, m) = list(map(int, input().split(' ')))
	M = []
	for i in range(n):
		M.append(list(map(int, input().split(' '))))
	lo = 0
	hi = n + m - 2
	total = 0
	while True:
		if lo >= hi:
			break
		num1 = 0
		num0 = 0
		for i in range(lo + 1):
			j = lo - i
			if i < n and j < m and (j >= 0):
				if M[i][j] == 1:
					num1 += 1
				else:
					num0 += 1
		for i in range(hi + 1):
			j = hi - i
			if i < n and j < m and (j >= 0):
				if M[i][j] == 1:
					num1 += 1
				else:
					num0 += 1
		total += min(num0, num1)
		lo += 1
		hi -= 1
	print(total)


t = int(input())
for i in range(t):
	(n, m) = map(int, input().split())
	mat = []
	for j in range(n):
		l = list(map(int, input().split()))
		mat.append(l)
	l = [[0, 0] for j in range(n + m - 1)]
	for j in range(n):
		for k in range(m):
			l[j + k][mat[j][k]] += 1
	tot = 0
	for j in range(0, (n + m - 1) // 2):
		x = n + m - 2 - j
		tot += min(l[j][0] + l[x][0], l[j][1] + l[x][1])
	print(tot)


import sys
for _ in range(int(sys.stdin.readline().rstrip())):
	(n, m) = list(map(int, sys.stdin.readline().rstrip().split()))
	mp = []
	for _ in range(n):
		ln = list(map(int, sys.stdin.readline().rstrip().split()))
		mp.append(ln)
	pv = int((n + m - 1) / 2)
	re = 0
	for i in range(pv):
		one = 0
		zero = 0
		for j in range(i + 1):
			x = j
			y = i - j
			if n - x - 1 < 0 or m - y - 1 < 0:
				continue
			if mp[x][y] == 0:
				zero += 1
			if mp[x][y] == 1:
				one += 1
			if mp[n - x - 1][m - y - 1] == 0:
				zero += 1
			if mp[n - x - 1][m - y - 1] == 1:
				one += 1
		re += min(one, zero)
	print(re)


t = int(input())
for s in range(t):
	(r, c) = map(int, input().split())
	matrix = []
	for i in range(r):
		array = list(map(int, input().split()))
		matrix.append(array)
	p = r + c - 2
	mid = p // 2
	if p % 2 == 0:
		lmid = p // 2
	else:
		lmid = p // 2 + 1
	if p % 2 == 0:
		visit = [[0, 0] for i in range(lmid + 1)]
	else:
		visit = [[0, 0] for i in range(lmid)]
	for j in range(r):
		for k in range(c):
			if j + k <= lmid - 1:
				if matrix[j][k] == 0:
					visit[j + k][0] += 1
				else:
					visit[j + k][1] += 1
			if j + k >= lmid:
				if matrix[j][k] == 0:
					visit[mid - (j + k - lmid)][0] += 1
				else:
					visit[mid - (j + k - lmid)][1] += 1
	add = 0
	if p % 2 == 1:
		for i in range(lmid):
			add += min(visit[i][0], visit[i][1])
	else:
		for i in range(lmid):
			add += min(visit[i][0], visit[i][1])
	print(add)


t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	dp = []
	for i in range(n):
		dp.append(list(map(int, input().split())))
	rq = n + m - 1
	zero = [0] * rq
	one = [0] * rq
	for i in range(n):
		for j in range(m):
			if dp[i][j] == 0:
				zero[i + j] += 1
			else:
				one[i + j] += 1
	ans = 0
	for i in range(rq // 2):
		ans += min(zero[i] + zero[rq - i - 1], one[i] + one[rq - i - 1])
	print(ans)


t = int(input())
for i in range(t):
	(n, m) = map(int, input().split())
	matrix = []
	count = 0
	for j in range(n):
		matrix.append(list(map(int, input().split())))
	t = n + m - 2
	if t % 2 == 1:
		t = int((t - 1) / 2) + 1
	else:
		t = int(t / 2)
	for x in range(0, t):
		d = {0: 0, 1: 0}
		for j in range(x + 1):
			if j <= n - 1 and x - j <= m - 1:
				if matrix[j][x - j] == 0:
					d[0] = d[0] + 1
				else:
					d[1] = d[1] + 1
			if n - 1 >= j and x - j <= m - 1:
				if matrix[n - 1 - j][m - 1 - (x - j)] == 0:
					d[0] = d[0] + 1
				else:
					d[1] = d[1] + 1
		if d[0] > d[1]:
			for j in range(x + 1):
				if j <= n - 1 and x - j <= m - 1:
					if matrix[j][x - j] != 0:
						count = count + 1
					matrix[j][x - j] = 0
					if matrix[n - 1 - j][m - 1 - (x - j)] != 0:
						count = count + 1
		else:
			for j in range(x + 1):
				if j <= n - 1 and x - j <= m - 1:
					if matrix[j][x - j] != 1:
						count = count + 1
					if matrix[n - 1 - j][m - 1 - (x - j)] != 1:
						count = count + 1
	print(count)


import sys

def input():
	return sys.stdin.readline().rstrip()

def input_split():
	return [int(i) for i in input().split()]
testCases = int(input())
answers = []

def inside(i, j, n, m):
	return 0 <= i <= n - 1 and 0 <= j <= m - 1
for _ in range(testCases):
	(n, m) = input_split()
	grid = []
	for i in range(n):
		grid.append(input_split())
	touched = [[False for i in range(m)] for j in range(n)]
	pending = [(0, 0)]
	changes = [(0, 1), (1, 0)]
	all_lists = []
	all_lists.append([grid[0][0]])
	while True:
		current_list = []
		new_pending = []
		for (pi, pj) in pending:
			for (ci, cj) in changes:
				if inside(pi + ci, pj + cj, n, m):
					if not touched[pi + ci][pj + cj]:
						new_pending.append((pi + ci, pj + cj))
						current_list.append(grid[pi + ci][pj + cj])
						touched[pi + ci][pj + cj] = True
		if len(current_list) == 0:
			break
		else:
			pending = new_pending
			all_lists.append(current_list.copy())
	if len(all_lists) % 2 == 1:
		all_lists = all_lists[:len(all_lists) // 2] + all_lists[len(all_lists) // 2 + 1:]
	ans = 0
	for i in range(len(all_lists) // 2):
		lis1 = all_lists[i]
		lis2 = all_lists[len(all_lists) - i - 1]
		(s1, l1) = (sum(lis1), len(lis1))
		(s2, l2) = (sum(lis2), len(lis2))
		ans += min(s1 + s2, l1 + l2 - (s1 + s2))
	answers.append(ans)
print(*answers, sep='\n')


t = int(input())
while t:
	t -= 1
	(n, m) = map(int, input().split(' '))
	d0 = {}
	d1 = {}
	for i in range(1, n + 1):
		l = list(map(int, input().split(' ')))
		for j in range(1, m + 1):
			x = i + j
			if x not in d0:
				d0[x] = 0
			if x not in d1:
				d1[x] = 0
			d0[x] += l[j - 1] == 0
			d1[x] += l[j - 1] == 1
	ans = 0
	i = 2
	j = n + m
	while i < j:
		x1 = d1[i] + d1[j]
		x2 = d0[i] + d0[j]
		i += 1
		j -= 1
		ans += min(x1, x2)
	print(ans)


from sys import stdin
input = stdin.readline
import bisect
import math
for xoxo in range(1):
	for _ in range(int(input())):
		a = []
		b = []
		g = []
		(n, m) = map(int, input().split())
		for i in range(n):
			t = list(map(int, input().split()))
			g.append(t)
		ans = 0
		for i in range((n + m - 1) // 2):
			(I, J) = (i, 0)
			if I >= n:
				J = i - (n - 1)
				I = n - 1
			t = []
			while J < m and I >= 0:
				t.append(g[I][J])
				I -= 1
				J += 1
			a.append(t)
		g1 = []
		for i in range(n - 1, -1, -1):
			g[i].reverse()
			g1.append(g[i])
		for i in range((n + m - 1) // 2):
			(I, J) = (i, 0)
			if I >= n:
				J = i - (n - 1)
				I = n - 1
			t = []
			while J < m and I >= 0:
				t.append(g1[I][J])
				I -= 1
				J += 1
			b.append(t)
		for i in range(len(a)):
			x = a[i].count(1) + b[i].count(1)
			tl = len(a[i]) * 2
			ans += min(x, tl - x)
		print(ans)


t = int(input())
for s in range(t):
	(n, m) = map(int, input().split())
	matrix = []
	change = 0
	for i in range(n):
		sub = list(map(int, input().split()))
		matrix.append(sub)
	l = 0
	o = n + m - 2
	for i in range((n + m - 1) // 2):
		pair = []
		for j in range(n):
			for k in range(m):
				if j + k == l or j + k == o:
					pair.append(matrix[j][k])
		if pair.count(0) >= pair.count(1):
			change += pair.count(1)
		else:
			change += pair.count(0)
		l += 1
		o -= 1
	print(change)


from collections import defaultdict
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	a = []
	d = defaultdict(list)
	for i in range(n):
		a.append(list(map(int, input().split())))
	for i in range(n):
		for j in range(m):
			d[i + j].append(a[i][j])
	ans = 0
	l = n + m - 1
	for i in range(l // 2):
		t = d[i] + d[n + m - i - 2]
		ans += min(t.count(0), t.count(1))
	print(ans)


from sys import stdin
input = stdin.buffer.readline
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	a = [[int(i) for i in input().split()] for j in range(n)]
	(s, l) = ([0] * (n + m - 2), [0] * (n + m - 2))
	for i in range(n):
		for j in range(m):
			if i + j == n + m - i - j - 2:
				continue
			x = min(i + j, n + m - 2 - i - j)
			s[x] += a[i][j] == 1
			l[x] += 1
	print(sum((min(s[x], l[x] - s[x]) for x in range(n + m - 2))))


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	a = [[] for i in range(n)]
	for i in range(n):
		a[i] = list(map(int, input().split()))
	ra = list(reversed([list(reversed(i)) for i in a]))
	ans = 0
	sm = (n + m - 1) // 2
	for s in range(sm):
		(cnt0, cnt1) = (0, 0)
		for i in range(s + 1):
			if i >= n:
				continue
			if s - i >= m:
				continue
			if a[i][s - i] == 0:
				cnt0 += 1
			if a[i][s - i] == 1:
				cnt1 += 1
			if ra[i][s - i] == 0:
				cnt0 += 1
			if ra[i][s - i] == 1:
				cnt1 += 1
		ans += min(cnt0, cnt1)
	print(ans)


inp = lambda : map(int, input().split(' '))
to_l = lambda x: list(x)
(t,) = inp()
for _ in range(t):
	(m, n) = inp()
	arr = []
	res = 0
	for _ in range(m):
		arr.append(to_l(inp()))
	for i in range((m + n - 1) // 2):
		counts = [0, 0]
		for j in range(0, i + 1):
			if (j >= 0 and j < m) and (i - j >= 0 and i - j < n):
				counts[arr[j][i - j]] += 1
			if (m - 1 - j >= 0 and m - 1 - j < m) and (n - 1 - (i - j) >= 0 and n - 1 - (i - j) < n):
				counts[arr[m - 1 - j][n - 1 - (i - j)]] += 1
		res += min(counts)
	print(res)


for t in range(int(input())):
	(n, m) = map(int, input().split())
	x = [list(input().split()) for i in range(n)]
	a = (m + n - 3) // 2
	v = [0] * (a + 1)
	s = 0
	for i in range(n):
		for j in range(m):
			if x[i][j] == '1':
				if i + j <= a:
					v[i + j] += 1
				elif m + n - i - j - 2 <= a:
					v[m + n - i - j - 2] += 1
	for k in range(a + 1):
		b = 2 * min(k + 1, min(m, n))
		s += min(v[k], b - v[k])
	print(s)


import sys
input = lambda : sys.stdin.readline().rstrip()
from collections import defaultdict, deque, Counter
t = int(input())

def bfs(x, y):
	queue = deque([(x, y)])
	d = [[None] * m for _ in range(n)]
	dis_dic = defaultdict(list)
	d[x][y] = 0
	dis_dic[0].append(matrix[0][0])
	while queue:
		(u, v) = queue.popleft()
		next_dot = [(u + 1, v), (u, v + 1)]
		for (p, q) in next_dot:
			if 0 <= p < n and 0 <= q < m and (d[p][q] is None):
				d[p][q] = d[u][v] + 1
				queue.append((p, q))
				dis_dic[d[p][q]].append(matrix[p][q])
	return dis_dic
for _ in range(t):
	(n, m) = map(int, input().split())
	matrix = []
	for _ in range(n):
		matrix.append([int(x) for x in input().split()])
	total = n + m - 1
	dis_dic = bfs(0, 0)
	ans = 0
	for i in range(total // 2):
		a = []
		for j in dis_dic[i]:
			a.append(j)
		for k in dis_dic[total - i - 1]:
			a.append(k)
		c = Counter(a)
		ans += sum(c.values()) - max(c.values())
	print(ans)


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	ar = []
	for i in range(n):
		ar.append(list(map(int, input().split())))
	le = n + m - 2
	ans = 0
	dic = {}
	for i in range(m):
		on = 0
		ze = 0
		for j in range(min(n, i + 1)):
			if ar[j][i - j] == 1:
				on += 1
			else:
				ze += 1
		dic[i] = [on, ze]
	for i in range(1, n):
		on = 0
		ze = 0
		for j in range(min(n - i, m)):
			if ar[i + j][m - 1 - j] == 1:
				on += 1
			else:
				ze += 1
		dic[m - 1 + i] = [on, ze]
	if le % 2 == 0:
		for i in range(le // 2):
			ans += min(dic[i][0] + dic[le - i][0], dic[i][1] + dic[le - i][1])
		print(ans)
	else:
		for i in range(le // 2 + 1):
			ans += min(dic[i][0] + dic[le - i][0], dic[i][1] + dic[le - i][1])
		print(ans)


from collections import defaultdict
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	a = [[*map(int, input().split())] for _ in range(n)]
	diag0 = defaultdict(int)
	diag1 = defaultdict(int)
	for i in range(n):
		for j in range(m):
			diag0[i + j] += int(a[i][j] == 0)
			diag1[i + j] += int(a[i][j] == 1)
	ans = 0
	diag0 = [*diag0.values()]
	diag1 = [*diag1.values()]
	if (n + m) % 2 == 0:
		del diag0[len(diag0) // 2]
		del diag1[len(diag0) // 2]
	l = len(diag1)
	for i in range(l // 2):
		ans += min(diag0[i] + diag0[l - i - 1], diag1[i] + diag1[l - i - 1])
	print(ans)


t = int(input())
for _ in range(t):
	(n, m) = (int(i) for i in input().split())
	a = []
	changes = 0
	for i in range(n):
		a.append([int(i) for i in input().split()])
	if n > m:
		a = [[a[j][i] for j in range(n)] for i in range(m)]
		(n, m) = (m, n)
	for idx in range((n + m - 1) // 2):
		j = idx
		i = 0
		diag = []
		while i < n and j >= 0:
			diag.append(a[i][j])
			diag.append(a[n - i - 1][m - j - 1])
			i += 1
			j -= 1
		changes += min(diag.count(1), diag.count(0))
	print(changes)


import sys
import heapq
import random
import collections
import math

def solve(grid):
	lst = collections.defaultdict(list)
	for (i, row) in enumerate(grid):
		for (j, val) in enumerate(row):
			lst[i + j].append(val)
	res = 0
	for i in range((max(lst) + 1) // 2):
		c = collections.Counter(lst[i]) + collections.Counter(lst[max(lst) - i])
		res += min(c[0], c[1])
	return res

def console(*args):
	print('\x1b[36m', *args, '\x1b[0m', file=sys.stderr)
	return
for case_num in range(int(input())):
	(nrows, m) = list(map(int, input().split()))
	grid = []
	for _ in range(nrows):
		grid.append(list(map(int, input().split())))
	res = solve(grid)
	print(res)


from collections import defaultdict as dd
import sys
input = sys.stdin.readline
t = int(input())
while t:
	(n, m) = map(int, input().split())
	ll = []
	for i in range(n):
		l = list(map(int, input().split()))
		ll.append(l)
	tot = n + m - 1
	ans = 0
	ind = -1
	if tot % 2 == 1:
		ind = tot // 2
	if m >= tot // 2:
		for jth in range(tot // 2):
			if jth == ind:
				continue
			i = 0
			j = jth
			c1 = 0
			c0 = 0
			while j >= 0 and i < n:
				if ll[i][j] == 0:
					c0 += 1
				else:
					c1 += 1
				i += 1
				j -= 1
			jj = m - jth - 1
			ii = n - 1
			while jj < m and ii >= 0:
				if ll[ii][jj] == 0:
					c0 += 1
				else:
					c1 += 1
				ii -= 1
				jj += 1
			ans += min(c0, c1)
	else:
		for ith in range(tot // 2):
			if ith == ind:
				continue
			i = ith
			j = 0
			c1 = 0
			c0 = 0
			while j < m and i >= 0:
				if ll[i][j] == 0:
					c0 += 1
				else:
					c1 += 1
				i -= 1
				j += 1
			jj = m - 1
			ii = n - ith - 1
			while jj >= 0 and ii < n:
				if ll[ii][jj] == 0:
					c0 += 1
				else:
					c1 += 1
				ii += 1
				jj -= 1
			ans += min(c0, c1)
	print(ans)
	t -= 1


t = int(input())
for case in range(t):
	(rows, cols) = map(int, input().split())
	w = []
	one_counts = [0] * (rows + cols - 1)
	zero_counts = [0] * (rows + cols - 1)
	for r in range(rows):
		row = [int(x) for x in input().split()]
		for c in range(cols):
			if row[c]:
				one_counts[r + c] += 1
			else:
				zero_counts[r + c] += 1
	total = 0
	for i in range(rows + cols - 1):
		if i == len(one_counts) - 1 - i:
			continue
		aggr_one = one_counts[i] + one_counts[-1 - i]
		aggr_zero = zero_counts[i] + zero_counts[-1 - i]
		total += min(aggr_one, aggr_zero)
	assert total % 2 == 0
	print(total // 2)


from sys import stdin
input = stdin.readline
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	mat = []
	for _ in range(n):
		mat.append(input().rstrip().split())
	d = []
	for col in range(m):
		t = []
		row = 0
		while col >= 0 and row < n:
			t += [mat[row][col]]
			col -= 1
			row += 1
		d.append(t)
	for row in range(1, n):
		t = []
		col = m - 1
		while col >= 0 and row < n:
			t += [mat[row][col]]
			col -= 1
			row += 1
		d.append(t)
	ans = 0
	ld = len(d)
	for i in range(ld // 2):
		temp = d[i].count('0') + d[ld - i - 1].count('0')
		if temp == len(d[i] + d[ld - i - 1]) or temp == 0:
			continue
		ans += min(len(d[i] + d[ld - i - 1]) - temp, temp)
	print(ans)


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	matrix = [list(map(int, input().split())) for i in range(n)]
	length = (n - 1) // 2 + (m - 1) // 2
	cnt = 0
	for l in range(0, length + (n * m % 2 == 0)):
		cur = []
		for i in range(n):
			for j in range(m):
				if i + j == l or n - 1 - i + m - 1 - j == l:
					cur.append([i, j])
		one = 0
		zero = 0
		for i in range(len(cur)):
			one += matrix[cur[i][0]][cur[i][1]] == 1
			zero += matrix[cur[i][0]][cur[i][1]] == 0
		cnt += min(one, zero)
	print(cnt)


import io, os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
import sys

def dist(X, Y):
	return abs(X[0] - Y[0]) + abs(X[1] - Y[1])

def solve(n, m, A):
	(start, goal) = ((0, 0), (n - 1, m - 1))
	D = [[] for _ in range(n + m + 1)]
	for x in range(n):
		for y in range(m):
			d = min(dist(start, (x, y)), dist(goal, (x, y)))
			id
			D[d].append(A[x][y])
	ans = 0
	if (n + m) % 2 == 0:
		end = (n + m - 2) // 2 - 1
	else:
		end = (n + m - 2) // 2
	for i in range(end + 1):
		Nums = D[i]
		l = len(Nums)
		s = sum(Nums)
		ans += min(s, l - s)
	return ans

def main():
	t = int(input())
	for _ in range(t):
		(n, m) = map(int, input().split())
		A = [tuple(map(int, input().split())) for _ in range(n)]
		ans = solve(n, m, A)
		sys.stdout.write(str(ans) + '\n')
main()


for _ in range(int(input())):
	(row, col) = map(int, input().split())
	mat = []
	for _ in range(row):
		mat.append([int(x) for x in input().split()])
	lst = [[] for _ in range(row + col - 1)]
	for i in range(row):
		for j in range(col):
			lst[i + j].append(mat[i][j])
	for i in range(len(lst) // 2):
		lst[i].extend(lst[-i - 1])
	lst = lst[:len(lst) // 2]
	ans = 0
	for i in lst:
		ans += min(i.count(0), i.count(1))
	print(ans)


import collections
tests = int(input())
for _ in range(tests):
	arr = [int(a) for a in input().strip().split(' ')]
	n = arr[0]
	m = arr[1]
	mat = []
	matinv = []
	for _ in range(n):
		arr = [int(a) for a in input().strip().split(' ')]
		mat.append(arr)
	c = 0
	val = []
	for sum in range((n + m - 1) // 2):
		ones = 0
		tots = sum + 1
		for strt in range(0, sum + 1):
			if strt >= n or sum - strt >= m:
				tots -= 1
				continue
			if mat[strt][sum - strt] == 1:
				ones += 1
			if mat[n - 1 - strt][m - 1 + strt - sum] == 1:
				ones += 1
		zeros = 2 * tots - ones
		c += min(ones, zeros)
	print(c)


def get_rows(grid):
	return [[c for c in r] for r in grid]

def get_cols(grid):
	return zip(*grid)

def get_forward_diagonals(grid):
	b = [None] * (len(grid) - 1)
	grid = [b[:i] + r + b[i:] for (i, r) in enumerate(get_rows(grid))]
	return [[c for c in r if c is not None] for r in get_cols(grid)]

def solve():
	(n, m) = map(int, input().split())
	arr = [list(map(int, input().split())) for _ in range(n)]
	ans = 0
	diags = get_forward_diagonals(arr)
	for i in range((m + n - 1) // 2):
		diags[i] += diags[-i - 1]
		zr = diags[i].count(0)
		ans += min(zr, len(diags[i]) - zr)
	print(ans)
t = int(input())
for _ in range(t):
	solve()


import os
import sys
debug = True
if debug and os.path.exists('input.in'):
	input = open('input.in', 'r').readline
else:
	debug = False
	input = sys.stdin.readline

def inp():
	return int(input())

def inlt():
	return list(map(int, input().split()))

def insr():
	s = input()
	return s[:len(s) - 1]

def invr():
	return map(int, input().split())
test_count = int(input())
for t in range(test_count):
	if debug:
		print('Test Case #', t + 1)
	(n, m) = invr()
	one_counts = {}
	zero_counts = {}
	for i in range(n):
		row = inlt()
		for j in range(m):
			index = i + j
			if index > (n + m - 2) // 2:
				index = n + m - 2 - index
			if row[j] == 1:
				one_counts[index] = one_counts.get(index, 0) + 1
			else:
				zero_counts[index] = zero_counts.get(index, 0) + 1
	ans = 0
	for i in range((n + m - 3) // 2 + 1):
		ans += min(one_counts.get(i, 0), zero_counts.get(i, 0))
	print(ans)


def f(n, m, A):
	ans = 0
	for k in range(int((n + m - 1) / 2)):
		num = [0, 0]
		for i in range(k + 1):
			if 0 <= i <= n - 1 and 0 <= k - i <= m - 1:
				num[A[i][k - i]] += 1
			if 0 <= n - 1 - i <= n - 1 and 0 <= m - 1 - k + i <= m - 1:
				num[A[n - 1 - i][m - 1 - k + i]] += 1
		ans += min(num)
	return ans
for i in range(int(input())):
	[n, m] = input().split(' ')
	(n, m) = (int(n), int(m))
	A = []
	for j in range(n):
		B = input().split(' ')
		for k in range(m):
			B[k] = int(B[k])
		A.append(B)
	print(f(n, m, A))


def gen(test):
	max_col = len(test[0])
	max_row = len(test)
	cols = [[] for _ in range(max_col)]
	rows = [[] for _ in range(max_row)]
	fdiag = [[] for _ in range(max_row + max_col - 1)]
	bdiag = [[] for _ in range(len(fdiag))]
	min_bdiag = -max_row + 1
	for x in range(max_col):
		for y in range(max_row):
			cols[x].append(test[y][x])
			rows[y].append(test[y][x])
			fdiag[x + y].append(test[y][x])
			bdiag[x - y - min_bdiag].append(test[y][x])
	return fdiag
for _ in range(int(input())):
	(n, m) = map(int, input().split(' '))
	arr = []
	for _ in range(n):
		arr.append([int(num) for num in input().split(' ')])
	p = gen(arr)
	k = len(p)
	ans = 0
	if k % 2 == 0:
		for i in range(k // 2):
			num = p[i] + p[k - 1 - i]
			ans = min(num.count(1), num.count(0)) + ans
	else:
		for i in range(k // 2):
			num = p[i] + p[k - 1 - i]
			ans = min(num.count(1), num.count(0)) + ans
	print(ans)


def zigzagTraversal(Matrix):
	n = len(Matrix)
	m = len(Matrix[0])
	zigzag = [[] for i in range(n + m - 1)]
	for i in range(n):
		for j in range(m):
			zigzag[i + j].append(Matrix[i][j])
	return zigzag

def rotate90(Matrix):
	n = len(Matrix)
	m = len(Matrix[0])
	Rotated = [[0 for i in range(n)] for j in range(m)]
	for i in range(m):
		Rotated[i] = [x[i] for x in Matrix][::-1]
	return Rotated

def rotate180(Matrix):
	n = len(Matrix)
	m = len(Matrix[0])
	Rotated = [[0 for i in range(m)] for j in range(n)]
	for i in range(n):
		Rotated[i] = Matrix[n - i - 1][::-1]
	return Rotated

def printMatrix(matrix):
	s = [[str(e) for e in row] for row in matrix]
	lens = [max(map(len, col)) for col in zip(*s)]
	fmt = '\t'.join(('{{:{}}}'.format(x) for x in lens))
	table = [fmt.format(*row) for row in s]
	print('_________________')
	print('\n'.join(table))
	print('`````````````````')
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	Matrix = []
	for i in range(n):
		temp = [int(x) for x in input().split()]
		Matrix.append(temp)
	rotated = rotate180(Matrix)
	Uno = zigzagTraversal(Matrix)
	Dos = zigzagTraversal(rotated)
	Ans = 0
	if n + m & 1:
		XX = (n + m) // 2
	else:
		XX = (n + m - 1) // 2
	for i in range(XX):
		zero = Uno[i].count(0)
		ones = Uno[i].count(1)
		zero += Dos[i].count(0)
		ones += Dos[i].count(1)
		Ans += min(zero, ones)
	print(Ans)


t = int(input())
for test in range(t):
	(n, m) = map(int, input().split())
	a = []
	for i in range(n):
		a.append(list(map(int, input().split())))
	cnt = [[0] * 2 for _ in range(n + m - 1)]
	for i in range(n):
		for j in range(m):
			cnt[i + j][a[i][j]] += 1
	ans = 0
	for i in range(n + m - 1):
		j = n + m - 2 - i
		if i < j:
			ans += min(cnt[i][0] + cnt[j][0], cnt[i][1] + cnt[j][1])
	print(ans)


def main():
	(n, m) = map(int, input().split())
	dct = dict()
	for i in range(n):
		line = list(map(int, input().split()))
		for k in range(m):
			to_wrt = i + k
			if i + k >= (n + m) // 2:
				to_wrt = n + m - to_wrt - 2
			if not to_wrt in dct:
				dct[to_wrt] = [0, 0]
			if line[k] == 0:
				dct[to_wrt][0] += 1
			else:
				dct[to_wrt][1] += 1
	change = 0
	for i in dct:
		change += min(dct[i])
	if (n + m) % 2 == 0:
		change -= min(dct[max(dct)])
	print(change)
t = int(input())
for i in range(t):
	main()


t = int(input())
from collections import deque, defaultdict
for i in range(t):
	(n, m) = map(int, input().split())
	l = []
	for j in range(n):
		l.append(list(map(int, input().split())))
	l1 = [[0, 0] for j in range(n * m + 1)]
	d = defaultdict(int)
	d1 = defaultdict(int)
	q = deque([])
	q.append((0, 0))
	d[0, 0] = 1
	d1[0, 0] = 0
	a = 0
	while len(q):
		cur = q.popleft()
		if l[cur[0]][cur[1]] == 1:
			l1[d1[cur]][1] += 1
		else:
			l1[d1[cur]][0] += 1
		a = max(a, d1[cur])
		if cur[0] != n - 1 and d[cur[0] + 1, cur[1]] == 0:
			q.append((cur[0] + 1, cur[1]))
			d[cur[0] + 1, cur[1]] = 1
			d1[cur[0] + 1, cur[1]] = d1[cur] + 1
		if cur[1] != m - 1 and d[cur[0], cur[1] + 1] == 0:
			q.append((cur[0], cur[1] + 1))
			d[cur[0], cur[1] + 1] = 1
			d1[cur[0], cur[1] + 1] = d1[cur] + 1
	l2 = []
	for j in range(a + 1):
		l2.append(j)
	l2.sort()
	ans = 0
	x = len(l2) - 1
	for i in range(len(l2) // 2):
		if l1[i][0] + l1[x - i][0] != 0 and l1[i][1] + l1[x - i][1] != 0:
			if l1[i][0] + l1[x - i][0] < l1[i][1] + l1[x - i][1]:
				ans += l1[i][0] + l1[x - i][0]
			else:
				ans += l1[i][1] + l1[x - i][1]
	print(ans)


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	mas = [list(map(int, input().split())) for i in range(n)]
	ans = 0
	for a in range((n + m - 1) // 2):
		t = [0, 0]
		for i in range(min(a + 1, n)):
			j = a - i
			if j >= m:
				continue
			t[mas[i][j]] += 1
			t[mas[-i - 1][-j - 1]] += 1
		ans += min(t)
	print(ans)


import sys
input = sys.stdin.readline
t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	field = []
	for _ in range(n):
		line = [int(item) for item in input().split()]
		field.append(line)
	num = (n + m - 1) // 2
	ret = 0
	for i in range(num):
		ones = 0
		zeros = 0
		x = max(0, i - m + 1)
		y = min(i, m - 1)
		for j in range(n):
			if field[x][y]:
				ones += 1
			else:
				zeros += 1
			x += 1
			y -= 1
			if x >= n or y < 0:
				break
		x = max(0, n - i - 1)
		y = min(m - 1 - i + n - 1, m - 1)
		for j in range(n):
			if field[x][y]:
				ones += 1
			else:
				zeros += 1
			x += 1
			y -= 1
			if x >= n or y < 0:
				break
		ret += min(zeros, ones)
	print(ret)


t = int(input())
for i in range(t):
	(n, m) = map(int, input().split())
	arr = list()
	answer = 0
	for j in range(n):
		arr.append([int(x) for x in input().split()])
	diag = n + m - 1
	for j in range(diag // 2):
		white = 0
		black = 0
		x = 0
		y = j
		if j > m - 1:
			x = j - m + 1
			y = m - 1
		while x < n and y >= 0:
			if arr[x][y] == 0:
				white += 1
			else:
				black += 1
			x += 1
			y -= 1
		x = n - 1
		y = m - j - 1
		if 0 > m - j - 1:
			x = n - 1 + m - j - 1
			y = 0
		while x >= 0 and y < m:
			if arr[x][y] == 0:
				white += 1
			else:
				black += 1
			x -= 1
			y += 1
		answer += min(white, black)
	print(answer)


from sys import stdin, stdout
import math
input = stdin.readline

def print(x='', end='\n'):
	stdout.write(str(x) + end)

def solve():
	(n, m) = map(int, input().split())
	ans = 0
	mat = []
	for i in range(n):
		mat.append(list(map(int, input().split())))
	for val in range((n + m - 1) // 2):
		(o, z) = (0, 0)
		for i in range(n):
			for j in range(m):
				if i + j == val or n - i - 1 + m - j - 1 == val:
					if mat[i][j]:
						o += 1
					else:
						z += 1
		ans += min(o, z)
	print(ans)
t = 1
t = int(input())
for _ in range(t):
	solve()


import math
T = int(input())
for _ in range(T):
	(n, m) = input().split()
	n = int(n)
	m = int(m)
	li = []
	ans = 0
	for i in range(n):
		temp = input().split()
		li.append(temp)
	if m >= n:
		for i in range(int((m + n - 1) / 2)):
			cnt0 = 0
			cnt1 = 0
			tpcnt0 = 0
			tpcnt1 = 0
			trm = i
			x = 0
			while trm >= 0 and x < n:
				if li[x][trm] == '1':
					cnt1 += 1
				else:
					cnt0 += 1
				trm -= 1
				x += 1
			trm = m - 1 - i
			x = n - 1
			while trm < m and x >= 0:
				if li[x][trm] == '1':
					tpcnt1 += 1
				else:
					tpcnt0 += 1
				x -= 1
				trm += 1
			ans += min(tpcnt0 + cnt0, cnt1 + tpcnt1)
	else:
		for i in range(int((n + m - 1) / 2)):
			cnt0 = 0
			cnt1 = 0
			tpcnt0 = 0
			tpcnt1 = 0
			trm = i
			x = 0
			while trm >= 0 and x < m:
				if li[trm][x] == '1':
					cnt1 += 1
				else:
					cnt0 += 1
				trm -= 1
				x += 1
			trm = n - 1 - i
			x = m - 1
			while trm < n and x >= 0:
				if li[trm][x] == '1':
					tpcnt1 += 1
				else:
					tpcnt0 += 1
				x -= 1
				trm += 1
			ans += min(tpcnt0 + cnt0, cnt1 + tpcnt1)
	print(ans)


t = int(input())
for _ in range(t):
	(n, m) = list(map(int, input().split()))
	a = [list(map(int, input().split())) for _ in range(n)]
	k = [0] * (n + m - 1)
	c = [0] * (n + m - 1)
	for i in range(n):
		for j in range(m):
			c[i + j] += 1
			if a[i][j] == 1:
				k[i + j] += 1
	ans = 0
	for i in range((n + m - 1) // 2):
		j = n + m - 2 - i
		ans += min(k[i] + k[j], c[i] + c[j] - k[i] - k[j])
	print(ans)


for nt in range(int(input())):
	(n, m) = map(int, input().split())
	mat = []
	for i in range(n):
		mat.append(list(map(int, input().split())))
	mid = []
	if (n + m) % 2 == 0:
		mid = [(n + m - 1) // 2]
	ans = 0
	count = {}
	for i in range(n):
		for j in range(m):
			if i + j not in count:
				(o, z) = (0, 0)
				s = (i, j)
				while s[0] < n and s[1] >= 0:
					if mat[s[0]][s[1]] == 1:
						o += 1
					else:
						z += 1
					s = (s[0] + 1, s[1] - 1)
				s = (i - 1, j + 1)
				while s[0] >= 0 and s[1] < m:
					if mat[s[0]][s[1]] == 1:
						o += 1
					else:
						z += 1
					s = (s[0] - 1, s[1] + 1)
				count[i + j] = (z, o)
	for i in count:
		if i not in mid:
			ans += min(count[i][0] + count[n + m - i - 2][0], count[i][1] + count[n + m - i - 2][1])
	print(ans // 2)


import sys
from functools import lru_cache, cmp_to_key
from heapq import merge, heapify, heappop, heappush, nsmallest
from math import ceil, floor, gcd, fabs, factorial, fmod, sqrt, inf
from collections import defaultdict as dd, deque, Counter as C
from itertools import combinations as comb, permutations as perm
from bisect import bisect_left as bl, bisect_right as br, bisect
from time import perf_counter
from fractions import Fraction
from decimal import Decimal
mod = pow(10, 9) + 7
mod2 = 998244353

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

def out(*var, end='\n'):
	sys.stdout.write(' '.join(map(str, var)) + end)

def l():
	return list(sp())

def sl():
	return list(ssp())

def sp():
	return map(int, data().split())

def ssp():
	return map(str, data().split())

def l1d(n, val=0):
	return [val for i in range(n)]

def l2d(n, m, val=0):
	return [l1d(n, val) for j in range(m)]

def valid(a, b):
	return 0 <= a < n and 0 <= b < m

def d1(p1, p2):
	return p1 + p2

def d2(p1, p2):
	return abs(n - 1 - p1) + abs(m - 1 - p2)
for _ in range(int(data())):
	(n, m) = sp()
	mat = []
	for i in range(n):
		mat.append(l())
	answer = 0
	path = n + m - 1
	for k in range(path):
		(i, j) = (0, k)
		(z, o) = (0, 0)
		while j >= 0:
			if valid(i, j) and mat[i][j] != -1 and (d1(i, j) != d2(i, j)):
				if mat[i][j]:
					o += 1
				else:
					z += 1
				mat[i][j] = -1
			(a, b) = (n - 1 - i, m - 1 - j)
			if valid(a, b) and mat[a][b] != -1 and (d1(a, b) != d2(a, b)):
				if mat[a][b]:
					o += 1
				else:
					z += 1
				mat[a][b] = -1
			i += 1
			j -= 1
		answer += min(z, o)
	out(answer)


from typing import DefaultDict
t = int(input())
for _ in range(t):
	matrix = []
	(n, m) = map(int, input().split())
	for row in range(n):
		l = list(map(int, input().split()))
		matrix.append(l)
	freq = {}
	for x in range(n):
		for y in range(m):
			if x + y not in freq:
				freq[x + y] = {1: 0, 0: 0}
			freq[x + y][matrix[x][y]] += 1
	change = 0
	for i in range((n + m - 1) // 2):
		change += min(freq[i][0] + freq[n + m - 2 - i][0], freq[i][1] + freq[n + m - 2 - i][1])
	print(change)


from sys import stdin, setrecursionlimit, stdout
from collections import deque
from math import sqrt, floor, ceil, log, log2, log10, pi, gcd, sin, cos, asin
from heapq import heapify, heappop, heappush, heappushpop, heapreplace

def ii():
	return int(stdin.readline())

def fi():
	return float(stdin.readline())

def mi():
	return map(int, stdin.readline().split())

def fmi():
	return map(float, stdin.readline().split())

def li():
	return list(mi())

def si():
	return stdin.readline().rstrip()

def lsi():
	return list(si())
res = ['YES', 'NO']
test_case = ii()
while test_case:
	test_case -= 1
	(n, m) = mi()
	a = []
	for _ in range(n):
		a.append(li())
	c = [[0, 0] for _ in range(n + m - 1)]
	for i in range(n):
		for j in range(m):
			c[i + j][a[i][j]] += 1
	s = 0
	for i in range(n + m - 1):
		(z, o) = c[i]
		if i < n + m - 2 - i:
			z += c[n + m - 2 - i][0]
			o += c[n + m - 2 - i][1]
		else:
			break
		s += min(o, z)
	print(s)


num_tests = int(input())
for _ in range(num_tests):
	(m, n) = map(int, input().split())
	pic = [list(map(int, input().split())) for _ in range(m)]
	res = 0
	path_len = m + n - 1
	for i in range(path_len // 2):
		values = 0
		counts = 0
		for x0 in range(i + 1):
			y0 = i - x0
			x1 = m - 1 - x0
			y1 = n - 1 - y0
			if x0 < m and y0 < n:
				values += pic[x0][y0]
				counts += 1
			if x1 >= 0 and y1 >= 0:
				values += pic[x1][y1]
				counts += 1
		res += min(values, counts - values)
	print(res)


from collections import defaultdict
import math
R = lambda : list(map(int, input().split(' ')))

def trevers(n, m):
	result = defaultdict(set)
	for i in range(n):
		for j in range(m):
			result[i + j].add((i, j))
	return result
(T,) = R()
for t in range(T):
	(n, m) = R()
	grid = []
	for i in range(n):
		grid.append(R())
	groups = trevers(n, m)
	result = 0
	for key in range(0, math.ceil((n + m - 2) / 2)):
		union = groups[key] | groups[n + m - 2 - key]
		ones = sum((grid[i][j] for (i, j) in union))
		result += min(ones, len(union) - ones)
	print(int(result))


import sys
from collections import deque, Counter
from itertools import product
T = int(input())
for _ in range(T):
	(n, m) = map(int, input().split())
	ls = [list(map(int, input().split())) for _ in range(n)]
	(cc0, cc1) = ([0] * (n + m - 1), [0] * (n + m - 1))
	for (i, j) in product(range(n), range(m)):
		if ls[i][j] == 0:
			cc0[i + j] += 1
		else:
			cc1[i + j] += 1
	res = 0
	for i in range((n + m - 1) // 2):
		(c0, c1) = (cc0[i] + cc0[-i - 1], cc1[i] + cc1[-i - 1])
		res += min(c0, c1)
	print(res)


from bisect import *
from collections import *
from math import gcd, ceil, sqrt, floor, inf
from heapq import *
from itertools import *
from operator import add, mul, sub, xor, truediv, floordiv
from functools import *
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())
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
farr = [1]
ifa = []

def fact(x, mod=0):
	if mod:
		while x >= len(farr):
			farr.append(farr[-1] * len(farr) % mod)
	else:
		while x >= len(farr):
			farr.append(farr[-1] * len(farr))
	return farr[x]

def ifact(x, mod):
	global ifa
	ifa.append(pow(farr[-1], mod - 2, mod))
	for i in range(x, 0, -1):
		ifa.append(ifa[-1] * i % mod)
	ifa = ifa[::-1]

def per(i, j, mod=0):
	if i < j:
		return 0
	if not mod:
		return fact(i) // fact(i - j)
	return farr[i] * ifa[i - j] % mod

def com(i, j, mod=0):
	if i < j:
		return 0
	if not mod:
		return per(i, j) // fact(j)
	return per(i, j, mod) * ifa[j] % mod

def catalan(n):
	return com(2 * n, n) // (n + 1)

def linc(f, t, l, r):
	while l < r:
		mid = (l + r) // 2
		if t > f(mid):
			l = mid + 1
		else:
			r = mid
	return l

def rinc(f, t, l, r):
	while l < r:
		mid = (l + r + 1) // 2
		if t < f(mid):
			r = mid - 1
		else:
			l = mid
	return l

def ldec(f, t, l, r):
	while l < r:
		mid = (l + r) // 2
		if t < f(mid):
			l = mid + 1
		else:
			r = mid
	return l

def rdec(f, t, l, r):
	while l < r:
		mid = (l + r + 1) // 2
		if t > f(mid):
			r = mid - 1
		else:
			l = mid
	return l

def isprime(n):
	for i in range(2, int(n ** 0.5) + 1):
		if n % i == 0:
			return False
	return True

def binfun(x):
	c = 0
	for w in arr:
		c += ceil(w / x)
	return c

def lowbit(n):
	return n & -n

def inverse(a, m):
	a %= m
	if a <= 1:
		return a
	return (1 - inverse(m, a) * m) // a % m

class BIT:

	def __init__(self, arr):
		self.arr = arr
		self.n = len(arr) - 1

	def update(self, x, v):
		while x <= self.n:
			self.arr[x] += v
			x += x & -x

	def query(self, x):
		ans = 0
		while x:
			ans += self.arr[x]
			x &= x - 1
		return ans

class DSU:

	def __init__(self, n):
		self.c = [-1] * n

	def same(self, x, y):
		return self.find(x) == self.find(y)

	def find(self, x):
		if self.c[x] < 0:
			return x
		self.c[x] = self.find(self.c[x])
		return self.c[x]

	def union(self, u, v):
		(u, v) = (self.find(u), self.find(v))
		if u == v:
			return False
		if self.c[u] < self.c[v]:
			(u, v) = (v, u)
		self.c[u] += self.c[v]
		self.c[v] = u
		return True

	def size(self, x):
		return -self.c[self.find(x)]

class UFS:

	def __init__(self, n):
		self.parent = [i for i in range(n)]
		self.ranks = [0] * n

	def find(self, x):
		if x != self.parent[x]:
			self.parent[x] = self.find(self.parent[x])
		return self.parent[x]

	def union(self, u, v):
		(pu, pv) = (self.find(u), self.find(v))
		if pu == pv:
			return False
		if self.ranks[pu] >= self.ranks[pv]:
			self.parent[pv] = pu
			if self.ranks[pv] == self.ranks[pu]:
				self.ranks[pu] += 1
		else:
			self.parent[pu] = pv

def Prime(n):
	c = 0
	prime = []
	flag = [0] * (n + 1)
	for i in range(2, n + 1):
		if not flag[i]:
			prime.append(i)
			c += 1
		for j in range(c):
			if i * prime[j] > n:
				break
			flag[i * prime[j]] = prime[j]
			if i % prime[j] == 0:
				break
	return prime

def dij(s, graph):
	d = {}
	d[s] = 0
	heap = [(0, s)]
	seen = set()
	while heap:
		(dis, u) = heappop(heap)
		if u in seen:
			continue
		for v in graph[u]:
			if v not in d or d[v] > d[u] + graph[u][v]:
				d[v] = d[u] + graph[u][v]
				heappush(heap, (d[v], v))
	return d

def GP(it):
	return [[ch, len(list(g))] for (ch, g) in groupby(it)]

class DLN:

	def __init__(self, val):
		self.val = val
		self.pre = None
		self.next = None
t = N()
for i in range(t):
	(n, m) = RL()
	a = []
	for i in range(n):
		a.append(RLL())
	q = deque([(0, 0)])
	vis = set()
	vis.add((0, 0))
	res = []
	while q:
		one = zero = 0
		for i in range(len(q)):
			(r, c) = q.popleft()
			if a[r][c] == 1:
				one += 1
			else:
				zero += 1
			for (nr, nc) in ((r + 1, c), (r, c + 1)):
				if nr < n and nc < m and ((nr, nc) not in vis):
					vis.add((nr, nc))
					q.append((nr, nc))
		res.append((one, zero))
	i = 0
	j = len(res) - 1
	ans = 0
	while i < j:
		one = res[i][0]
		zero = res[i][1]
		one += res[j][0]
		zero += res[j][1]
		ans += min(one, zero)
		i += 1
		j -= 1
	print(ans)


from collections import defaultdict
t = int(input())
for i in range(t):
	(n, m) = map(int, input().split())
	l = []
	count = 0
	ones = defaultdict(int)
	zeros = defaultdict(int)
	s = (n + m - 2) // 2
	for i in range(n):
		l.append(list(map(int, input().split())))
	for i in range(n):
		for j in range(m):
			if l[i][j] == 0:
				zeros[i + j] += 1
			else:
				ones[i + j] += 1
	for i in range(s + 1):
		if i != n + m - 2 - i:
			count += min(ones[i] + ones[n + m - i - 2], zeros[i] + zeros[m + n - 2 - i])
	print(count)


import math, sys, bisect, heapq
from collections import defaultdict, Counter, deque
from itertools import groupby, accumulate
input = iter(sys.stdin.buffer.read().decode().splitlines()).__next__
ilele = lambda : map(int, input().split())
alele = lambda : list(map(int, input().split()))

def Y(c):
	print(['NO', 'YES'][c])

def y(c):
	print(['no', 'yes'][c])

def Yy(c):
	print(['No', 'Yes'][c])
for _ in range(int(input())):
	(n, m) = ilele()
	A = []
	for i in range(n):
		B = alele()
		A.append(B)
	Ans = [[0, 0].copy() for i in range(n + m - 1)]
	final = 0
	for i in range(n):
		for j in range(m):
			Ans[i + j][A[i][j]] += 1
	for i in range((n + m - 1) // 2):
		final += min(Ans[i][0] + Ans[-i - 1][0], Ans[i][1] + Ans[-i - 1][1])
	print(final)


import sys
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	k = n + m - 1
	dd = [[] for i in range(k)]
	tb = [list(map(int, input().split())) for i in range(n)]
	for x in range(n):
		for y in range(m):
			dd[x + y].append(tb[x][y])
	ans = 0
	for i in range(k // 2):
		n1 = len(dd[i]) + len(dd[-1 - i])
		n2 = sum(dd[i]) + sum(dd[-1 - i])
		ans += min(n2, n1 - n2)
	print(ans)


import math
t = int(input())
for i in range(t):
	inp = list(map(int, input().split()))
	n = inp[0]
	m = inp[1]
	matrix = []
	for j in range(n):
		inp1 = list(map(int, input().split()))
		matrix.append(inp1)
	arr = [0] * (n + m - 1)
	arr2 = [0] * (n + m - 1)
	for i in range(n):
		for j in range(m):
			if i + j != n + m - i - j - 2:
				arr[min(i + j, n + m - i - j - 2)] += matrix[i][j]
				arr2[min(i + j, n + m - i - j - 2)] += 1
	ans = 0
	for i in range(len(arr)):
		ans += min(arr[i], arr2[i] - arr[i])
	print(ans)


def help():
	(n, m) = map(int, input().split(' '))
	arr = []
	for i in range(n):
		arr.append(list(map(int, input().split(' '))))
	queue = []
	visited = [[-1] * m for i in range(n)]
	queue.append((0, 0))
	visited[0][0] = 0
	while queue:
		curr = queue.pop(0)
		if curr[0] + 1 < n and visited[curr[0] + 1][curr[1]] == -1:
			queue.append((curr[0] + 1, curr[1]))
			visited[curr[0] + 1][curr[1]] = visited[curr[0]][curr[1]] + 1
		if curr[1] + 1 < m and visited[curr[0]][curr[1] + 1] == -1:
			queue.append((curr[0], curr[1] + 1))
			visited[curr[0]][curr[1] + 1] = visited[curr[0]][curr[1]] + 1
	for i in range(n):
		for j in range(m):
			visited[i][j] = min(visited[i][j], n + m - 2 - visited[i][j])
	distances = {}
	for i in range(n):
		for j in range(m):
			cd = visited[i][j]
			if arr[i][j] == 1:
				distances[cd] = (distances.get(cd, (0, 0))[0], distances.get(cd, (0, 0))[1] + 1)
			if arr[i][j] == 0:
				distances[cd] = (distances.get(cd, (0, 0))[0] + 1, distances.get(cd, (0, 0))[1])
	ans = 0
	for i in distances:
		if i == (n + m - 2) / 2:
			continue
		ans += min(distances[i][0], distances[i][1])
	print(ans)
for _ in range(int(input())):
	help()


import math
from collections import defaultdict

def r():
	return int(input())

def rm():
	return map(int, input().split())

def rl():
	return list(map(int, input().split()))
for _ in range(r()):
	(n, m) = rm()
	a = []
	b = defaultdict(int)
	c = defaultdict(int)
	for i in range(n):
		d = rl()
		for j in range(m):
			b[min(i + j, n + m - i - j - 2)] += d[j]
			c[min(i + j, n + m - i - j - 2)] += 1
	ans = 0
	if n + m - 1 & 1:
		d = (n + m - 2) // 2
	else:
		d = (n + m - 2) // 2 + 1
	for i in range(d):
		ans += min(b[i], c[i] - b[i])
	print(ans)


import os
os_input = os.read(0, int(10000000.0)).split()
os_input_pos = -1
answer_list = []

def read_s():
	global os_input_pos
	os_input_pos += 1
	return os_input[os_input_pos].decode()

def read_i():
	return int(read_s())

def write_s(v):
	answer_list.append(v)

def write_i(v):
	write_s(str(v))

def print_ans():
	os.write(1, '\n'.join(answer_list).encode())
	os.write(1, '\n'.encode())
T = read_i()
while T:
	T -= 1
	n = read_i()
	m = read_i()
	a = [[read_i() for j in range(m)] for i in range(n)]
	L = 0
	R = n - 1 + m - 1
	ans = 0
	while L < R:
		count = [0, 0]
		for i in range(n):
			for j in range(m):
				if i + j == L or i + j == R:
					count[a[i][j]] += 1
		ans += min(count)
		L += 1
		R -= 1
	write_i(ans)
print_ans()


from sys import stdin, stdout
from math import gcd, sqrt
from collections import deque
input = stdin.readline
R = lambda : map(int, input().split())
I = lambda : int(input())
S = lambda : input().rstrip('\n')
L = lambda : list(R())
P = lambda x: stdout.write(x)
hg = lambda x, y: (y + x - 1) // x * x
pw = lambda x: 1 if x == 1 else 1 + pw(x // 2)
chk = lambda x: chk(x // 2) if not x % 2 else True if x == 1 else False
dgnl = lambda x: sqrt(2 * x ** 2)

def cnt(r, c, x, y, rn):
	stk = [(r, c)]
	v[0][a[r][c]] += 1
	m = []
	for i in range(rn):
		while stk:
			(r, c) = stk.pop()
			if val[r + x][c] and a[r + x][c] != '#':
				val[r + x][c] = 0
				m += ((r + x, c),)
				v[i + 1][a[r + x][c]] += 1
			if val[r][c + y] and a[r][c + y] != '#':
				val[r][c + y] = 0
				m += ((r, c + y),)
				v[i + 1][a[r][c + y]] += 1
		stk = m.copy()
		m = []
for _ in range(I()):
	(r, c) = R()
	a = [['#'] * (c + 2)]
	for i in range(r):
		a.append(['#'] + L() + ['#'])
	a.append(['#'] * (c + 2))
	mn = (r + c - 1) // 2
	v = [[0, 0] for i in range(mn)]
	val = [[1] * (c + 2) for i in range(r + 2)]
	cnt(1, 1, 1, 1, mn - 1)
	cnt(r, c, -1, -1, mn - 1)
	ans = 0
	for i in v:
		ans += min(i)
	print(ans)


import sys

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

def idata():
	return [int(x) for x in ii().split()]

def solve_of_problem():
	(n, m) = idata()
	data = [(0, 0)] * (m + n - 1)
	for i in range(n):
		a = idata()
		for j in range(m):
			data[i + j] = (data[i + j][0] + 1, data[i + j][1] + a[j])
	ans = 0
	for i in range((m + n - 1) // 2):
		ans += min(data[i][1] + data[m + n - 2 - i][1], data[i][0] + data[m + n - 2 - i][0] - data[i][1] - data[m + n - 2 - i][1])
	print(ans)
	return
for ______ in range(int(ii())):
	solve_of_problem()


def solve_test_case(t):
	(n, m) = parse_array(int)
	grid = []
	for i in range(n):
		grid.append(parse_array(int))
	dist_start_to_points = {}
	dist_end_to_points = {}
	dist_start_to_points[0] = set()
	dist_start_to_points[0].add((0, 0))
	for d in range(1, n + m):
		dist_start_to_points[d] = set()
		for (i, j) in dist_start_to_points[d - 1]:
			if i + 1 < n:
				dist_start_to_points[d].add((i + 1, j))
			if j + 1 < m:
				dist_start_to_points[d].add((i, j + 1))
	dist_end_to_points[0] = set()
	dist_end_to_points[0].add((n - 1, m - 1))
	for d in range(1, n + m):
		dist_end_to_points[d] = set()
		for (i, j) in dist_end_to_points[d - 1]:
			if i - 1 >= 0:
				dist_end_to_points[d].add((i - 1, j))
			if j - 1 >= 0:
				dist_end_to_points[d].add((i, j - 1))
	res = 0
	for d in range((n + m) // 2):
		if dist_start_to_points[d] == dist_end_to_points[d]:
			break
		num_1 = 0
		num_0 = 0
		for (i, j) in dist_start_to_points[d]:
			if grid[i][j] == 1:
				num_1 += 1
			else:
				num_0 += 1
		for (i, j) in dist_end_to_points[d]:
			if grid[i][j] == 1:
				num_1 += 1
			else:
				num_0 += 1
		res += min(num_1, num_0)
	print(res)

def parse_array(f):
	return list(map(f, input().split()))

def solve():
	T = int(input())
	for t in range(T):
		solve_test_case(t)
solve()


T = int(input())
for test in range(T):
	(n, m) = map(int, input().split())
	a = [[int(j) for j in input().split()] for i in range(n)]
	temp = []
	for i in range(n + m - 1):
		temp.append([0, 0])
	for i in range(n):
		for j in range(m):
			temp[i + j][a[i][j]] += 1
	ans = 0
	for i in range(n + m - 1):
		j = n + m - 2 - i
		if i > j:
			ans += min(temp[i][0] + temp[j][0], temp[i][1] + temp[j][1])
	print(ans)


def solve():
	(n, m) = map(int, input().split())
	a = [list(map(int, input().split())) for _ in range(n)]
	dc = [[0, 0] for _ in range(0 + 0, n - 1 + m - 1 + 1)]
	for i in range(n):
		for j in range(m):
			dc[i + j][a[i][j]] += 1
	ans = 0
	for i in range(len(dc) // 2):
		j = len(dc) - 1 - i
		ans += min(dc[i][0] + dc[j][0], dc[i][1] + dc[j][1])
	print(ans)
t = int(input())
for _ in range(t):
	solve()


testing_mode = True
import sys, traceback
test_data = ''
final_output = ''

def input(input_format=0, multi=0):
	if multi > 0:
		return [input(input_format) for x in range(multi)]
	else:
		next_line = next(test_data, None).strip() if test_data else sys.stdin.readline()
		if input_format == 0:
			formatted_input = [next_line]
		elif input_format == 1:
			formatted_input = list(map(int, next_line.split()))
		elif input_format == 2:
			formatted_input = list(map(float, next_line.split()))
		elif input_format == 3:
			formatted_input = next_line.split()
		elif input_format == 4:
			formatted_input = (lambda x: [x[0], list(map(int, x[1:]))])(next_line.split())
		elif input_format == 5:
			formatted_input = (lambda x: [x[0], list(map(float, x[1:]))])(next_line.split())
		else:
			formatted_input = [next_line]
		return formatted_input

def log(*args):
	if testing_mode:
		print(*args)

def out(output_line, output_format=0, newline=True):
	global final_output
	formatted_output = ''
	if output_format == 0:
		formatted_output = str(output_line)
	elif output_format == 1:
		formatted_output = ' '.join(map(str, output_line))
	elif output_format == 1:
		formatted_output = '\n'.join(map(str, output_line))
	if testing_mode:
		final_output += formatted_output + '\n' * newline
	else:
		print(formatted_output, end='\n' if newline else '')
test_inputs = ['\n4\n2 2\n1 1\n0 1\n2 3\n1 1 0\n1 0 0\n3 7\n1 0 1 1 1 1 1\n0 0 0 0 0 0 0\n1 1 1 1 1 0 1\n3 5\n1 0 1 0 0\n1 1 1 1 0\n0 0 1 0 0\n\n', '\n5\n1 1\n1\n1 5\n1 1 1 0 0\n3 4\n0 0 0 0\n1 1 1 1\n0 0 0 0\n4 3\n0 1 0\n0 1 0\n0 1 0\n0 1 0\n5 1\n0\n0\n1\n1\n1\n', '\n$$$\n', '\n$$$\n']
test_outputs = ['\n0\n3\n4\n4\n\n', '\n0\n2\n4\n4\n2\n', '\n$$$\n', '\n$$$\n']

def solve():
	for z in range(input(1)[0]):
		(n, m) = input(1)
		k = input(1, n)
		if m < n:
			kn = []
			for i in range(m):
				p = []
				for j in range(n):
					p.append(k[j][i])
				kn.append(p)
			k = kn
			(n, m) = (m, n)
		log(k, n, m)
		t = 0
		e = set()
		for i in range(max(n, m)):
			log(i)
			c = [0, 0]
			if (n + m) % 2 == 0:
				u = int((n - 1) / 2 + (m - 1) / 2)
				if i == u:
					log('u', u)
					continue
			for j in range(i + 1):
				x1 = i - j
				y1 = j
				x2 = m - x1 - 1
				y2 = n - y1 - 1
				if x1 in e and y1 == 0:
					log(e)
					break
				if x1 >= m or y1 >= n:
					log(x1, y1, 'br')
					break
				log([x1, y1], [x2, y2], n, m)
				if y2 == 0:
					e.add(x2)
				c[k[y1][x1]] += 1
				c[k[y2][x2]] += 1
			t += min(c)
		out(t)
		log()
	return

def run_all(overwrite_testing=False):
	global testing_mode, final_output, test_data
	testing_mode = overwrite_testing and testing_mode
	if testing_mode:
		tests_failed = 0
		for (test_number, (test_in, test_out)) in enumerate(zip(test_inputs, test_outputs)):
			final_output = ''
			if test_in.lstrip()[:3] == '$$$':
				continue
			test_data = iter([i for i in test_in.split('\n') if i])
			print(f'Test Case #{test_number + 1}:')
			print('<' * 20)
			fail = False
			verdict = '\x1b[92m\x1b[1mPASS\x1b[0m'
			try:
				solve()
				final = final_output.rstrip('\n')
				raw_out = iter(map(str, final.split('\n'))) if final else iter(())
			except Exception:
				raw_out = ''
				fail = True
				print('\x1b[95m')
				traceback.print_exc()
				print('\x1b[0m')
			if raw_out:
				if test_out.lstrip()[:3] == '$$$':
					verdict = '\x1b[94m\x1b[1mSKIP\x1b[0m'
					print('\x1b[94m' + '\n'.join(list(raw_out)) + '\x1b[0m')
				else:
					for line_out in [i for i in test_out.split('\n') if i]:
						line_raw = next(raw_out, '% None %')
						if line_raw == line_out.strip():
							print(f'\x1b[92m{line_raw}\x1b[0m')
						else:
							print(f'\x1b[91m{line_raw}\x1b[0m')
							fail = True
					line_raw = next(raw_out, None)
					while line_raw:
						print(f'\x1b[91m{line_raw}\x1b[0m')
						line_raw = next(raw_out, None)
						fail = True
			print('>' * 20)
			if fail:
				verdict = '\x1b[91m\x1b[1mFAIL\x1b[0m'
				tests_failed += 1
			print(verdict + '\n')
		if tests_failed:
			print(f"\x1b[91m\x1b[1m{tests_failed} TEST{('S' if tests_failed > 1 else '')} FAILED!\x1b[0m")
		else:
			print(f'\x1b[92m\x1b[1mALL TESTS PASSED!\x1b[0m')
	else:
		test_data = False
		solve()
run_all(False)


import sys
input = sys.stdin.buffer.readline
T = int(input())
for _ in range(T):
	(n, m) = map(int, input().split())
	a = []
	for i in range(n):
		a.append(list(map(int, input().split())))
	if (n, m) == (1, 1):
		print(0)
	else:
		s = [0] * 100
		one = [0] * 100
		ex = -1
		if (n + m) % 2 == 0:
			ex = (n + m - 2) // 2
		for i in range(n):
			for j in range(m):
				d = min(i + j, n + m - 2 - (i + j))
				if d == ex:
					continue
				s[d] += 1
				if a[i][j] == 1:
					one[d] += 1
		res = 0
		for i in range(100):
			res += min(one[i], s[i] - one[i])
		print(res)


import sys
input = sys.stdin.buffer.readline
t = int(input())
from collections import deque
for _ in range(t):
	(n, m) = map(int, input().split())
	A = [list(map(int, input().split())) for _ in range(n)]
	R = [[0, 0] for _ in range(n + m - 1)]
	q = deque()
	visit = [[-1] * m for _ in range(n)]
	visit[0][0] = 0
	q.append((0, 0))
	while q:
		(u, v) = q.popleft()
		for (du, dv) in ((0, 1), (1, 0)):
			(nu, nv) = (u + du, v + dv)
			if 0 <= nu <= n - 1 and 0 <= nv <= m - 1:
				if visit[nu][nv] == -1:
					visit[nu][nv] = visit[u][v] + 1
					q.append((nu, nv))
	for i in range(n):
		for j in range(m):
			if A[i][j] == 0:
				R[visit[i][j]][0] += 1
			else:
				R[visit[i][j]][1] += 1
	ans = 0
	for i in range(n + m - 1):
		j = n + m - 2 - i
		if i == j:
			continue
		else:
			ans += min(R[i][1] + R[j][1], R[i][0] + R[j][0])
	print(ans // 2)


import sys
import collections as cc
import bisect as bi
I = lambda : list(map(int, input().split()))
for tc in range(int(input())):
	(n, m) = I()
	a = []
	for i in range(n):
		a.append(I())
	temp = [[0, 0] for i in range(n + m + 1)]
	tem = set()
	for i in range(n):
		for j in range(m):
			tem.add(i + j)
			temp[i + j][a[i][j]] += 1
	tem = sorted(tem)
	ans = 0
	nn = len(tem)
	for i in range(len(tem) // 2):
		aa = temp[tem[i]]
		bb = temp[tem[nn - i - 1]]
		ans += min(aa[0] + bb[0], aa[1] + bb[1])
	print(ans)


def solve(n, m):
	ans = 0
	s = [list(map(int, input().split())) for _ in range(n)]
	diag_num = n + m - 1
	for i in range(diag_num // 2):
		sum = 0
		for j in range(n):
			k = i - j
			if 0 <= j < n and 0 <= k < m:
				sum += s[j][k]
		i2 = diag_num - i - 1
		for j in range(n):
			k = i2 - j
			if 0 <= j < n and 0 <= k < m:
				sum += s[j][k]
		y = min(i + 1, n, m)
		ans += min(sum, 2 * y - sum)
	print(ans)
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	solve(n, m)


t = int(input())
for uu in range(t):
	(n, m) = map(int, input().split())
	matrix = []
	for i in range(n):
		matrix.append(list(map(int, input().split())))
	count1 = [0 for i in range(n + m - 1)]
	count0 = [0 for i in range(n + m - 1)]
	for i in range(n + m):
		if i < m:
			i1 = i
			j1 = 0
		else:
			i1 = m - 1
			j1 = i - m + 1
		while j1 < n and i1 >= 0:
			count1[i] += matrix[j1][i1]
			count0[i] += 1 - matrix[j1][i1]
			i1 -= 1
			j1 += 1
	ans = 0
	for i in range((n + m - 1) // 2):
		ans += min(count1[i] + count1[n + m - 2 - i], count0[i] + count0[n + m - 2 - i])
	print(ans)


def diag(lis):
	for line in range(1, n + m):
		start_col = max(0, line - n)
		count = min(line, m - start_col, n)
		aa = []
		for j in range(0, count):
			aa.append(lis[min(n, line) - j - 1][start_col + j])
		a.append(aa)
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	lis = []
	a = []
	for i in range(n):
		li = list(map(int, input().split()))
		lis.append(li)
	diag(lis)
	n = len(a) // 2
	ans = 0
	for i in range(n):
		if i == len(a) - i - 1:
			break
		zer = a[i].count(0) + a[len(a) - i - 1].count(0)
		one = a[i].count(1) + a[len(a) - i - 1].count(1)
		ans += min(zer, one)
	print(ans)


from math import *

def r1(t):
	return t(input())

def r2(t):
	return [t(i) for i in input().split()]

def r3(t):
	return [t(i) for i in input()]
for _ in range(r1(int)):
	(n, m) = r2(int)
	t = (n + m - 1) // 2
	a = []
	for i in range(n):
		a.append(r2(int))
	ans = 0
	for k in range(t):
		s = 0
		cnt = 0
		cp = [max(0, k - m + 1), min(k, m - 1)]
		while cp[0] < n and cp[1] >= 0:
			s += a[cp[0]][cp[1]]
			cp[0] += 1
			cp[1] -= 1
			cnt += 1
		cp = [n - 1 - max(0, k - m + 1), max(m - k - 1, 0)]
		while cp[0] >= 0 and cp[1] < m:
			s += a[cp[0]][cp[1]]
			cp[0] -= 1
			cp[1] += 1
			cnt += 1
		ans += min(s, cnt - s)
	print(ans)


import math
t = int(input())
for i in range(t):
	(n, m) = list(map(int, input().split()))
	matrix = []
	for i in range(n):
		lis = list(map(int, input().split()))
		matrix.append(lis)
	a = math.ceil((n + m - 1) / 2)
	lis = [[] for j in range(a)]
	for j in range(n):
		for k in range(m):
			if j + k + 1 <= a:
				lis[j + k].append(matrix[j][k])
			else:
				lis[n + m - (j + k) - 2].append(matrix[j][k])
	arr = [[] for j in range(a)]
	for j in range(a):
		arr[j].append(lis[j].count(0))
		arr[j].append(lis[j].count(1))
	if (n + m) % 2 == 0:
		ans = 0
		for j in range(a - 1):
			ans += min(arr[j][0], arr[j][1])
		print(ans)
	else:
		ans = 0
		for j in range(a):
			ans += min(arr[j][0], arr[j][1])
		print(ans)


T = int(input())
for _ in range(T):
	(n, m) = list(map(int, input().split()))
	arr = []
	for i in range(n):
		arr.append(list(map(int, input().split())))
	k = n + m - 1
	ct = [[0] * 2 for i in range(k)]
	for i in range(n):
		for j in range(m):
			if arr[i][j] == 0:
				ct[i + j][0] += 1
			else:
				ct[i + j][1] += 1
	pd = 0
	for i in range(k // 2):
		pd += min(ct[i][0] + ct[k - i - 1][0], ct[i][1] + ct[k - i - 1][1])
	print(pd)


for _ in range(int(input())):
	(n, m) = list(map(int, input().split()))
	max_ = 100
	zeroes = [0] * max_
	ones = [0] * max_
	for i in range(1, n + 1):
		row = list(map(int, input().split()))
		for j in range(1, m + 1):
			ai = row[j - 1]
			pos1 = i - 1 + j - 1
			pos2 = n - i + m - j
			if pos1 == pos2:
				continue
			pos = min(pos1, pos2)
			if ai == 0:
				zeroes[pos] += 1
			else:
				ones[pos] += 1
	ans = 0
	for i in range(max_):
		ans += min(zeroes[i], ones[i])
	print(ans)


from collections import defaultdict
dx = [-1, 1, 0, 0]
dy = [0, 0, 1, -1]
for _ in range(int(input())):
	(n, m) = list(map(int, input().split()))
	mat = []
	for i in range(n):
		mat.append(list(map(int, input().split())))
	dist = [[1000000 for i in range(m)] for j in range(n)]
	vis = [[False for i in range(m)] for j in range(n)]
	path = defaultdict(list)
	dist[0][0] = 0
	path[0].append(mat[0][0])
	q = [[0, 0]]
	vis[0][0] = True
	while q != []:
		u = q[0]
		q.pop(0)
		(x, y) = (u[0], u[1])
		for i in range(4):
			nx = x + dx[i]
			ny = y + dy[i]
			if nx >= 0 and nx < n and (ny < m) and (ny >= 0):
				if vis[nx][ny] == False:
					dist[nx][ny] = min(dist[nx][ny], dist[x][y] + 1)
					path[dist[nx][ny]].append(mat[nx][ny])
					q.append([nx, ny])
					vis[nx][ny] = True
				dist[nx][ny] = min(dist[nx][ny], dist[x][y] + 1)
	ans = 0
	uni = list(path.keys())
	x = max(uni) + 1
	last = x - 1
	for i in range(x // 2):
		val1 = path[i].count(0)
		val2 = path[i].count(1)
		val1 += path[last].count(0)
		val2 += path[last].count(1)
		last -= 1
		ans += min(val1, val2)
	print(ans)


import os
import sys
from io import BytesIO, IOBase
import math

def inputIntArray():
	return list(map(int, input().rstrip().split()))

def inputArray():
	return input().rstrip().split()

def inputVars():
	return map(int, input().rstrip().split())

def inputNum():
	return int(input())

def main():
	for _ in range(inputNum()):
		(row, col) = inputVars()
		matrix = []
		noOfZeroes = [0] * (row + col - 1)
		noOfOnes = [0] * (row + col - 1)
		for rowPos in range(row):
			matrix.append(inputIntArray())
			for colPos in range(col):
				if matrix[rowPos][colPos]:
					noOfOnes[rowPos + colPos] += 1
				else:
					noOfZeroes[rowPos + colPos] += 1
		halfOfMatrix = (row + col - 2) // 2
		minChanges = 0
		for pos in range(halfOfMatrix + 1):
			if pos != halfOfMatrix or (row + col) % 2 != 0:
				ones = noOfOnes[pos] + noOfOnes[row + col - 2 - pos]
				zeroes = noOfZeroes[pos] + noOfZeroes[row + col - 2 - pos]
				minChanges += min(ones, zeroes)
		print(minChanges)
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()


for _ in range(int(input())):
	(n, m) = list(map(int, input().split()))
	a = []
	for i in range(n):
		a.append(list(map(int, input().split())))
	ans = 0
	for i in range((n + m - 1) // 2):
		zeros = 0
		ones = 0
		for j in range(0, i + 1):
			x = i - j
			y = j
			if x < m and y < n:
				if a[y][x] == 1:
					ones += 1
				else:
					zeros += 1
			if m - x - 1 >= 0 and n - y - 1 >= 0:
				if a[n - y - 1][m - x - 1] == 1:
					ones += 1
				else:
					zeros += 1
		ans += min(zeros, ones)
	print(ans)


from collections import *
import sys
from bisect import *
input = sys.stdin.readline
from math import *
t = int(input())
while t:
	t -= 1
	(n, m) = map(int, input().split())
	r = []
	for i in range(n):
		a = list(map(int, input().split()))
		r.append(a)
	res = [[0, 0] for i in range(n + m - 1)]
	for i in range(n):
		for j in range(m):
			res[i + j][int(r[i][j])] += 1
	s = 0
	for i in range(len(res) // 2):
		s += min(res[i][0] + res[-1 - i][0], res[i][1] + res[-1 - i][1])
	print(s)


t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	a = []
	for i in range(n):
		a.append(list(map(int, input().split())))
	d = dict()
	for i in range(1, n + 1):
		for j in range(1, m + 1):
			k = min(i - 1 + j - 1, n - i + m - j)
			if d.get(k, None) == None:
				d[k] = [0, 0]
			d[k][a[i - 1][j - 1]] += 1
	ans = 0
	for (k, v) in d.items():
		if n + m & 1 == 0 and k == (n + m - 2) // 2:
			continue
		ans += min(v[0], v[1])
	print(ans)


for _ in range(int(input())):
	(n, m) = list(map(int, input().split()))
	arr = []
	fl = False
	if n > m:
		fl = True
		for i in range(m):
			arr.append([0] * n)
	for i in range(n):
		if fl:
			nArr = list(map(int, input().split()))
			for g in range(m):
				arr[g][i] = nArr[g]
		else:
			arr.append(list(map(int, input().split())))
	if fl:
		(n, m) = (m, n)
	p = n + m - 1
	t = 0
	for i in range(p // 2):
		ones = 0
		nulls = 0
		gotNow = 0
		for g in range(min(i + 1, n)):
			gotNow += arr[g][i - g]
			gotNow += arr[n - g - 1][m - i - 1 + g]
		if gotNow < min(i + 1, n):
			t += gotNow
		else:
			t += min(i + 1, n) * 2 - gotNow
	print(t)


import sys, math

def ii():
	return int(input())

def mii():
	return map(int, input().split())

def lmii():
	return list(mii())

def main():
	for _ in range(ii()):
		(n, m) = mii()
		x = []
		ans = 0
		for i in range(n):
			x.append(lmii())
		p = n + m - 1
		zero = [0] * p
		one = [0] * p
		for i in range(n):
			for j in range(m):
				if x[i][j] == 1:
					one[i + j] += 1
				if x[i][j] == 0:
					zero[i + j] += 1
		for i in range(p // 2):
			zo = zero[i] + zero[p - 1 - i]
			on = one[i] + one[p - 1 - i]
			ans += min(zo, on)
		print(ans)
main()


def main():
	(n, m) = map(int, input().split())
	matrix = []
	for _ in range(n):
		row = list(map(int, input().split()))
		matrix.append(row)
	cnt = [[] for _ in range(n + m - 1)]
	for i in range(n):
		for j in range(m):
			cnt[i + j].append(matrix[i][j])
	ans = 0
	for k in range(n + m - 1):
		l = n + m - k - 2
		if k >= l:
			continue
		else:
			c = len(cnt[k])
			ans += min(c - sum(cnt[k]) + c - sum(cnt[l]), sum(cnt[k]) + sum(cnt[l]))
	print(ans)
for _ in range(int(input())):
	main()


for _ in range(int(input())):
	(n, m) = [int(num) for num in input().split()]
	matrix = []
	for i in range(n):
		matrix.append([int(x) for x in input().split()])
	ans = 0
	shit = [[] for i in range(m + n - 1)]
	for i in range(n):
		for j in range(m):
			shit[i + j].append(matrix[i][j])
	for i in range((m + n - 1) // 2):
		ans += min(shit[i].count(1) + shit[-1 - i].count(1), shit[i].count(0) + shit[-1 - i].count(0))
	print(ans)


t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	matrix = []
	for _ in range(n):
		matrix.append(list(map(int, input().split())))
	cost = 0
	for j in range((n + m - 1) // 2):
		first_diag = []
		second_diag = []
		for i in range(j + 1):
			if 0 <= i < n and 0 <= j - i < m:
				first_diag.append(matrix[i][j - i])
			if 0 <= n - 1 - i < n and 0 <= m - 1 - j + i < m:
				second_diag.append(matrix[n - 1 - i][m - 1 - j + i])
		ones = sum(first_diag) + sum(second_diag)
		cost += min(ones, len(first_diag) + len(second_diag) - ones)
	print(cost)


def ParseDiagonal(matrix, r, c):
	ones = 0
	zeros = 0
	if matrix[r][c] == 1:
		ones += 1
	else:
		zeros += 1
	matrix[r][c] = 0
	topr = r
	topc = c
	rr = r - 1
	cc = c + 1
	while rr > -1 and cc < len(matrix[0]):
		if matrix[rr][cc] == 1:
			ones = ones + 1
		else:
			zeros = zeros + 1
		matrix[rr][cc] = 0
		topr = rr
		topc = cc
		rr -= 1
		cc += 1
	r = r + 1
	c = c - 1
	while r < len(matrix) and c > -1:
		if matrix[r][c] == 1:
			ones += 1
		else:
			zeros += 1
		matrix[r][c] = 0
		r += 1
		c -= 1
	return (zeros, ones, topr, topc)
t = int(input())
for testcase in range(t):
	(n, m) = map(int, input().split())
	matrix = []
	for i in range(n):
		u = list(map(int, input().split()))
		matrix.append(u)
	n = n - 1
	m = m - 1
	a = 0
	b = 0
	answer = 0
	while True:
		(z, o, topr, topc) = ParseDiagonal(matrix, a, b)
		(zz, oo, topr2, topc2) = ParseDiagonal(matrix, n, m)
		zeros = z + zz
		ones = o + oo
		if topr == topr2 and topc == topc2:
			break
		if zeros != 0 and ones != 0:
			answer += min(zeros, ones)
		if b == len(matrix[0]) - 1:
			a += 1
		else:
			b += 1
		if m == 0:
			n -= 1
		else:
			m -= 1
		if a > len(matrix) - 1:
			break
		if n < 0:
			break
	print(answer)


t = int(input())
for i in range(t):
	(n, m) = map(int, input().split())
	arr = []
	for k in range(n):
		arr.append(list(map(int, input().split())))
	diagonals = [[0, 0] for t in range(n + m - 1)]
	diaglen = n + m - 1
	start = 0
	for col in range(m):
		for row in range(n):
			if arr[row][col] == 1:
				diagonals[start + row][1] += 1
			else:
				diagonals[start + row][0] += 1
		start += 1
	cntr = 0
	for t in range(diaglen // 2):
		zeros = diagonals[t][0] + diagonals[-(t + 1)][0]
		ones = diagonals[t][1] + diagonals[-(t + 1)][1]
		if zeros >= ones:
			cntr += ones
		else:
			cntr += zeros
	print(cntr)


import sys
input = sys.stdin.buffer.readline

def getAns(arr, n, m):
	maxPathLen = n + m - 2
	cnts = [[0, 0] for _ in range(maxPathLen + 1)]
	for i in range(n):
		for j in range(m):
			pathLen = i + j
			cnts[pathLen][arr[i][j]] += 1
	halfPathCnts = [[0, 0] for _ in range(maxPathLen // 2 + 1)]
	minChange = 0
	for i in range(maxPathLen // 2 + 1):
		j = maxPathLen - i
		if i != j:
			halfPathCnts[i][0] = cnts[i][0] + cnts[j][0]
			halfPathCnts[i][1] = cnts[i][1] + cnts[j][1]
			minChange += min(halfPathCnts[i])
		else:
			pass
	return minChange
t = int(input())
for __ in range(t):
	(n, m) = [int(x) for x in input().split()]
	arr = []
	for _ in range(n):
		arr.append([int(x) for x in input().split()])
	print(getAns(arr, n, m))


import sys

def input():
	return sys.stdin.readline()[:-1]

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

def NM():
	return map(int, input().split())

def L():
	return list(NM())

def LN(n):
	return [N() for i in range(n)]

def LL(n):
	return [L() for i in range(n)]
t = N()

def dfs(x, y, d):
	if c[x][y]:
		return
	dep[d][l[x][y]] += 1
	c[x][y] = 1
	if x < n - 1:
		dfs(x + 1, y, d + 1)
	if y < m - 1:
		dfs(x, y + 1, d + 1)
for _ in range(t):
	(n, m) = NM()
	l = LL(n)
	dep = [[0, 0] for i in range(n + m)]
	c = [[0] * m for i in range(n)]
	dfs(0, 0, 0)
	ans = 0
	for i in range((n + m - 1) // 2):
		zero = dep[i][0] + dep[n + m - 2 - i][0]
		one = dep[i][1] + dep[n + m - 2 - i][1]
		ans += min(one, zero)
	print(ans)


dirs = [(0, 1), (1, 0), (0, -1), (-1, 0)]

def solve(matrix, n, m):
	lst = [(0, 0), (n - 1, m - 1)]
	visited = set(lst)
	res = 0 if matrix[0][0] == matrix[-1][-1] else 1
	while len(visited) < n * m:
		new_lst = []
		counts = 0
		for i in range(len(lst)):
			(cr, cc) = lst[i]
			for (r, c) in dirs:
				(nr, nc) = (cr + r, cc + c)
				if 0 <= nr < n and 0 <= nc < m and ((nr, nc) not in visited):
					visited.add((nr, nc))
					new_lst.append((nr, nc))
					if matrix[nr][nc] == 0:
						counts += 1
		last_res = res
		res += min(counts, len(new_lst) - counts)
		lst = new_lst
	if (n + m) % 2 == 0:
		return last_res
	else:
		return res
t = int(input())
for _ in range(t):
	(n, m) = list(map(int, input().split()))
	matrix = []
	for _ in range(n):
		matrix.append(list(map(int, input().split())))
	print(solve(matrix, n, m))


y = int(input())
ans = []
for i in range(y):
	al = input().split()
	m = list(map(int, al))
	a = m[0]
	b = m[1]
	q = []
	f = 0
	if a % 2 != b % 2:
		f = 1
	d = int((b + a - 1) / 2)
	for j in range(a):
		al = input().split()
		m = list(map(int, al))
		q.append(m)
	t = 0
	t1 = 0
	z = min(a, b)
	x = max(a, b)
	r = []
	r.append([0] * (a + b - 1))
	r.append([0] * (a + b - 1))
	for j in range(a):
		for k in range(b):
			if q[j][k] != q[a - 1 - j][b - 1 - k]:
				t += 1
			if q[j][k] == 1:
				r[1][j + k] += 1
			else:
				r[0][j + k] += 1
	l = int((a + b - 1) / 2)
	for j in range(l):
		t1 += min(r[0][j] + r[0][a + b - 2 - j], r[1][j] + r[1][a + b - 2 - j])
	ans.append(int(t1))
for i in ans:
	print(i)


t = int(input())
for ingles in range(t):
	X = input()
	X1 = X.split()
	n = int(X1[0])
	m = int(X1[1])
	A = []
	for i in range(n):
		l = input()
		A.append(l.split())
	L1 = [0] * (m + n - 1)
	L0 = [0] * (m + n - 1)
	for i in range(n):
		for j in range(m):
			if A[i][j] == '1':
				L1[i + j] += 1
			else:
				L0[i + j] += 1
	ex = int((n + m - 1) / 2)
	P1 = [0] * ex
	P0 = [0] * ex
	for i in range(ex):
		P1[i] = L1[i] + L1[-i - 1]
		P0[i] = L0[i] + L0[-i - 1]
	sum = 0
	for i in range(int((n + m - 1) / 2)):
		sum = sum + min(P0[i], P1[i])
	print(sum)


t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	g = []
	for i in range(n):
		g.append(list(map(int, input().split())))
	d = []
	for i in range(n):
		d.append([0] * m)
	for i in range(n):
		for j in range(m):
			if not (i == 0 and j == 0):
				if i == 0:
					d[i][j] = d[i][j - 1] + 1
				else:
					d[i][j] = d[i - 1][j] + 1
	ans = 0
	for k in range(n + m - 1):
		(c1, c0) = (0, 0)
		for i in range(n):
			for j in range(m):
				if (d[i][j] == k or d[i][j] == n + m - 2 - k) and k != n + m - 2 - k:
					if g[i][j] == 1:
						c1 += 1
					else:
						c0 += 1
		ans = ans + min(c1, c0)
	print(ans // 2)


t = int(input())
for i in range(t):
	(n, m) = map(int, input().split())
	matrix = []
	for j in range(n):
		matrix.append(list(map(int, input().split())))
	swapCount = 0
	diagonalInConcern = int((n + m - 1) / 2)
	for j in range(diagonalInConcern):
		numberOfZero = 0
		numberOfOne = 0
		for k in range(n):
			if k >= 0 and k < n and (j - k >= 0) and (j - k < m) and (matrix[k][j - k] == 0):
				numberOfZero += 1
			if k >= 0 and k < n and (j - k >= 0) and (j - k < m) and (matrix[k][j - k] == 1):
				numberOfOne += 1
			if n - 1 - k >= 0 and n - 1 - k < n and (m - 1 - j + k >= 0) and (m - 1 - j + k < m) and (matrix[n - 1 - k][m - 1 - j + k] == 0):
				numberOfZero += 1
			if n - 1 - k >= 0 and n - 1 - k < n and (m - 1 - j + k >= 0) and (m - 1 - j + k < m) and (matrix[n - 1 - k][m - 1 - j + k] == 1):
				numberOfOne += 1
		swapCount += min(numberOfOne, numberOfZero)
	print(swapCount)


def solve(n, m, mat):
	dist = [[0, 0] for _ in range(n + m - 1)]
	q = [(0, 0)]
	while q:
		q2 = []
		while q:
			(r, c) = q.pop()
			dist[r + c][mat[r][c]] += 1
			if r + 1 < n and (r + 1, c) not in q2:
				q2.append((r + 1, c))
			if c + 1 < m and (r, c + 1) not in q2:
				q2.append((r, c + 1))
		q = q2
	sol = 0
	for i in range(len(dist) // 2):
		zeros = dist[i][0] + dist[len(dist) - i - 1][0]
		ones = dist[i][1] + dist[len(dist) - i - 1][1]
		sol += min(zeros, ones)
	return sol
t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	mat = []
	for _ in range(n):
		row = list(map(int, input().split()))
		mat.append(row)
	print(solve(n, m, mat))


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	arr = []
	dp = [[0] * 2 for i in range((n + m - 1) // 2 + 1)]
	for i in range(n):
		arr.append(list(map(int, input().split())))
	for i in range(n):
		for j in range(m):
			c = i + j
			if i + j > (n + m - 2) // 2:
				c = n - i - 1 + m - j - 1
			if arr[i][j] == 1:
				dp[c][1] += 1
			else:
				dp[c][0] += 1
	c = 0
	for i in range((n + m - 1) // 2 + 1):
		if (n + m - 1) % 2 == 1 and i == (n + m - 1) // 2:
			continue
		c += min(dp[i][0], dp[i][1])
	print(c)


nb_test = int(input())
for t in range(nb_test):
	(n, m) = [int(x) for x in input().split()]
	matrix = [[0 for x in range(m)] for y in range(n)]
	for a in range(n):
		matrix[a] = [int(x) for x in input().split()]
	if n > m:
		matrix_t = [[0 for x in range(n)] for y in range(m)]
		for i in range(n):
			for j in range(m):
				matrix_t[j][i] = matrix[i][j]
		matrix = matrix_t.copy()
		temp = n
		n = m
		m = temp
	min_cell = 0
	for i in range(n - 1):
		sum_cell = 0
		for d in range(i + 1):
			sum_cell += matrix[d][i - d]
			sum_cell += matrix[n - d - 1][m - (i - d) - 1]
		min_cell += min(sum_cell, 2 * (i + 1) - sum_cell)
	for i in range(n - 1, n - 1 + int((m - (n - 1)) / 2)):
		sum_cell = 0
		for d in range(n):
			sum_cell += matrix[d][i - d]
			sum_cell += matrix[n - d - 1][m - (i - d) - 1]
		min_cell += min(sum_cell, 2 * n - sum_cell)
	print(min_cell)


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	a = [list(map(int, input().split())) for _ in range(n)]
	b = [[] for _ in range(n + m)]
	for i in range(n):
		for j in range(m):
			d = min(i + j, n - 1 - i + (m - 1 - j))
			b[d] += (a[i][j],)
	ans = 0
	for d in range((n + m - 1) // 2):
		c = {}
		for x in b[d]:
			c[x] = c.get(x, 0) + 1
		ans += len(b[d]) - max(c.values())
	print(ans)


from sys import stdin as sin
kk = int(input())
for _ in range(kk):
	data = sin.readline().rstrip()
	(n, m) = (int(i) for i in data.split(' '))
	matrix = []
	for _ in range(n):
		line = list((int(i) for i in sin.readline().rstrip().split(' ')))
		matrix.append(line)
	count = 0
	for s in range((m + n - 1) // 2):
		count_0 = 0
		count_1 = 0
		for i in range(s + 1):
			j = s - i
			if i < n and j < m:
				if matrix[i][j] == 0:
					count_0 += 1
				else:
					count_1 += 1
			if 0 <= n - i - 1 and 0 <= m - j - 1:
				if matrix[n - i - 1][m - j - 1] == 0:
					count_0 += 1
				else:
					count_1 += 1
		count += min(count_0, count_1)
	print(count)


T = int(input())
directions = [[0, 1], [0, -1], [1, 0], [-1, 0]]
while T > 0:
	(n, m) = map(int, input().split())
	matrix = []
	for i in range(n):
		arr = list(map(int, input().split()))
		matrix.append(arr)
	visited = [[False for i in range(m)] for j in range(n)]
	visited[0][0] = True
	visited[n - 1][m - 1] = True
	res = 0
	if matrix[0][0] != matrix[n - 1][m - 1]:
		res += 1
	(left_corner, right_corner) = ([[0, 0]], [[n - 1, m - 1]])
	al_steps = m + n - 2
	step = 1
	while step < (al_steps + 1) // 2:
		ones = 0
		zeros = 0
		le = len(left_corner)
		while le > 0:
			tmp = left_corner.pop(0)
			for direction in directions:
				(x, y) = (tmp[0] + direction[0], tmp[1] + direction[1])
				if x >= 0 and x < n and (y >= 0) and (y < m) and (visited[x][y] is False):
					visited[x][y] = True
					left_corner.append([x, y])
					if matrix[x][y] == 1:
						ones += 1
					else:
						zeros += 1
			tmp = right_corner.pop(0)
			for direction in directions:
				(x, y) = (tmp[0] + direction[0], tmp[1] + direction[1])
				if x >= 0 and x < n and (y >= 0) and (y < m) and (visited[x][y] is False):
					visited[x][y] = True
					right_corner.append([x, y])
					if matrix[x][y] == 1:
						ones += 1
					else:
						zeros += 1
			le -= 1
		res += min(ones, zeros)
		step += 1
	print(res)
	T -= 1


t = int(input())
for _ in range(t):
	(r, c) = map(int, input().split())
	arr = [list(map(int, input().split())) for i in range(r)]
	l = r + c - 1
	Arr = [[] for i in range(l)]
	ans = 0
	for i in range(r):
		for j in range(c):
			Arr[i + j].append(arr[i][j])
	for i in range(l // 2):
		t = Arr[i] + Arr[-1 - i]
		ans += min(t.count(0), t.count(1))
	print(ans)


import sys
T = int(sys.stdin.readline())
for _ in range(T):
	(n, m) = map(int, sys.stdin.readline().split())
	list_map = [list(map(int, sys.stdin.readline().split())) for _ in range(n)]
	aa = n + m - 1
	list_cell = [[0, 0] for _ in range(aa)]
	for y in range(n):
		for x in range(m):
			list_cell[y + x][list_map[y][x]] += 1
	result = 0
	for i in range(aa // 2):
		if aa - i - 1 == i:
			continue
		result += min(list_cell[i][0] + list_cell[aa - i - 1][0], list_cell[i][1] + list_cell[aa - i - 1][1])
	print(result)


def know(first, second):
	return min(first[0] + second[0], first[1] + second[1])
t = int(input())
for test in range(t):
	(n, m) = map(int, input().split())
	arr = []
	for i in range(n):
		arr.append(list(map(int, input().split())))
	ans = [[0, 0] for i in range(n + m - 1)]
	for i in range(n):
		for j in range(m):
			if arr[i][j] == 0:
				ans[i + j][0] += 1
			else:
				ans[i + j][1] += 1
	answer = 0
	for i in range(len(ans) // 2):
		answer += know(ans[i], ans[len(ans) - 1 - i])
	print(answer)


from collections import defaultdict
t = int(input())
rr = lambda : input()
rri = lambda : int(input())
rrm = lambda : list(map(int, input().split()))

def solve(N, M, grid):
	start = set([(0, 0)])
	end = set([(N - 1, M - 1)])
	valid = True
	changes = 0
	allstart = set()
	allend = set()
	while valid:
		startcount = defaultdict(int)
		endcount = defaultdict(int)
		for (y, x) in start:
			startcount[grid[y][x]] += 1
		for (y, x) in end:
			endcount[grid[y][x]] += 1
		changes += min(startcount[0] + endcount[0], startcount[1] + endcount[1])
		newstart = set()
		for (y, x) in start:
			for (iy, ix) in [(1, 0), (0, 1)]:
				iy += y
				ix += x
				if 0 <= ix < M and 0 <= iy < N:
					newstart.add((iy, ix))
					allstart.add((iy, ix))
		newend = set()
		for (y, x) in end:
			for (iy, ix) in [(-1, 0), (0, -1)]:
				iy += y
				ix += x
				if 0 <= ix < M and 0 <= iy < N:
					newend.add((iy, ix))
					allend.add((iy, ix))
		start = newstart
		end = newend
		if len(allstart & allend) > 0:
			valid = False
			break
	return changes
for _ in range(t):
	(n, m) = rrm()
	grid = []
	for _ in range(n):
		grid.append(rrm())
	print(solve(n, m, grid))


t = int(input())
for i in range(0, t):
	L = []
	nm = input().split()
	n = int(nm[0])
	m = int(nm[1])
	for i in range(0, n):
		M = list(map(int, input().split()))
		L.append(M)
	N = [[0 for i in range(n + m - 1)] for j in range(2)]
	sum = 0
	for i in range(0, n):
		for j in range(0, m):
			if L[i][j] == 0:
				N[0][i + j] += 1
			else:
				N[1][i + j] += 1
	for i in range(0, (n + m - 1) // 2):
		sum += min(N[0][i] + N[0][n + m - 2 - i], N[1][i] + N[1][n + m - 2 - i])
	print(sum)


T = int(input())
for _ in range(T):
	(n, m) = map(int, input().strip().split())
	path_length = n + m - 1
	g = []
	for _ in range(n):
		row = map(int, input().strip().split())
		g.append(list(row))
	starts = [(0, 0)]
	ends = [(n - 1, m - 1)]
	curr_length = 1
	total_changes = 0
	while curr_length < path_length // 2 + 1:
		steps = {0: 0, 1: 0}
		for s in starts:
			(l, r) = s
			steps[g[l][r]] += 1
		for e in ends:
			(l, r) = e
			steps[g[l][r]] += 1
		ones = steps[1]
		zeros = steps[0]
		total_changes += min(ones, zeros)
		new_starts = set()
		for s in starts:
			(l, r) = s
			if l + 1 < n:
				new_starts.add((l + 1, r))
			if r + 1 < m:
				new_starts.add((l, r + 1))
		new_ends = set()
		for e in ends:
			(l, r) = e
			if l - 1 >= 0:
				new_ends.add((l - 1, r))
			if r - 1 >= 0:
				new_ends.add((l, r - 1))
		starts = new_starts
		ends = new_ends
		curr_length += 1
	print(total_changes)


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	grid = [list(map(int, input().split())) for _ in range(n)]
	columns = [[grid[i][x - i] for i in range(x + 1) if i < n and x - i < m] for x in range(n + m - 1)]
	if len(columns) % 2 == 1:
		columns.pop(len(columns) // 2)
	co2 = list(reversed(columns))
	ans = 0
	for i in range(len(columns)):
		tot = columns[i] + co2[i]
		ans += len(tot) - max((tot.count(a) for a in set(tot)))
	print(ans // 2)


import time, math, bisect, sys
from sys import stdin, stdout
from collections import deque
from fractions import Fraction
from collections import Counter
pi = 3.141592653589793

def II():
	return int(stdin.readline())

def IO():
	return stdin.readline()

def IP():
	return map(int, stdin.readline().split())

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

def P(x):
	return stdout.write(str(x) + '\n')

def PI(x, y):
	return stdout.write(str(x) + ' ' + str(y) + '\n')

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

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

def readTree():
	v = int(input())
	adj = [set() for i in range(v + 1)]
	for i in range(v - 1):
		(u1, u2) = In()
		adj[u1].add(u2)
		adj[u2].add(u1)
	return (adj, v)

def bfs(adj, v):
	visited = [False] * (v + 1)
	q = deque()
	while q:
		pass

def solve():
	(n, m) = IP()
	li = []
	for i in range(n):
		temp = L()
		li.append(temp)
	l = [[0, 0] for i in range(n + m - 1)]
	for i in range(n):
		(x, y) = (i, 0)
		while y < m and x > -1:
			if li[x][y] == 1:
				l[i][1] += 1
			else:
				l[i][0] += 1
			x -= 1
			y += 1
	k = 1
	for i in range(n, n + m - 1, 1):
		(x, y) = (n - 1, k)
		while x > -1 and y < m:
			if li[x][y] == 1:
				l[i][1] += 1
			else:
				l[i][0] += 1
			x -= 1
			y += 1
		k += 1
	changes = 0
	(x, y) = (0, n + m - 2)
	while x < y:
		(zero, one) = (l[x][0] + l[y][0], l[x][1] + l[y][1])
		if zero > one:
			changes += one
		else:
			changes += zero
		x += 1
		y -= 1
	print(changes)
t = II()
for i in range(t):
	solve()


def answer(n, m, A):
	l = [[(0, 0)]]
	l1 = [[(n - 1, m - 1)]]
	while True:
		s = []
		s1 = []
		for i in l[-1]:
			if i[1] + 1 < m:
				s.append((i[0], i[1] + 1))
			if i[0] + 1 < n:
				s.append((i[0] + 1, i[1]))
		for i in l1[-1]:
			if i[1] - 1 >= 0:
				s1.append((i[0], i[1] - 1))
			if i[0] - 1 >= 0:
				s1.append((i[0] - 1, i[1]))
		s = set(s)
		s1 = set(s1)
		if s1 == s or set(l[-1]) == s1 or set(l1[-1]) == s:
			break
		l.append(list(s))
		l1.append(list(s1))
	ans = 0
	for i in range(len(l)):
		count = 0
		count1 = 0
		for j in range(len(l[i])):
			if A[l[i][j][0]][l[i][j][1]] == 1:
				count += 1
			else:
				count1 += 1
			if A[l1[i][j][0]][l1[i][j][1]] == 1:
				count += 1
			else:
				count1 += 1
		ans += min(count, count1)
	return ans
t = int(input())
for i in range(t):
	(n, m) = map(int, input().split())
	l = []
	for i in range(n):
		l.append(list(map(int, input().split())))
	print(answer(n, m, l))


import sys

def solve(arr, n, m):
	min_d = min(n, m)
	l = n + m
	half = (l - 1) // 2
	tot_changed = 0
	for d in range(half):
		(nz, no) = (0, 0)
		roff = 0 if n <= m else max(0, d - min_d + 1)
		for r in range(roff, min(min_d, d + 1) + roff):
			if arr[r][d - r] == 0:
				nz += 1
			else:
				no += 1
		for r in range(roff, min(min_d, d + 1) + roff):
			if arr[n - 1 - r][m - 1 - (d - r)] == 0:
				nz += 1
			else:
				no += 1
		if no == 0 or nz == 0:
			pass
		elif no == nz or no < nz:
			tot_changed += no
		else:
			tot_changed += nz
	return tot_changed
IN = [x.strip() for x in sys.stdin.readlines()]
T = int(IN[0])
cur = 1
for ti in range(T):
	(n, m) = [int(x) for x in IN[cur].split(' ')]
	arr = []
	for i in range(n):
		arr.append([int(x) for x in IN[1 + cur + i].split(' ')])
	result = solve(arr, n, m)
	print(result)
	cur += 1 + n


def solve(arr):
	t = []
	maxV = 0
	for i in range(len(arr)):
		temp = []
		for j in range(len(arr[i])):
			val = i + j
			if val > (len(arr) - 1 + len(arr[i]) - 1) // 2:
				val = len(arr) - 1 + len(arr[i]) - 1 - val
			if val > maxV:
				maxV = val
			temp.append(val)
		t.append(temp)
	groupNo = i + j + 1
	pail = []
	for i in range(maxV + 1):
		pail.append([])
	for i in range(len(arr)):
		for j in range(len(arr[i])):
			pos = t[i][j]
			pail[pos].append(arr[i][j])
	if groupNo % 2 == 1:
		del pail[-1]
	changeCount = 0
	for (i, line) in enumerate(pail):
		zero = 0
		one = 0
		for elem in line:
			if elem == 1:
				one += 1
			else:
				zero += 1
		if zero == 0 or one == 0:
			continue
		else:
			changeCount += min(one, zero)
	return changeCount
input()
while True:
	try:
		val = input().split(' ')
		for i in range(len(val)):
			val[i] = int(val[i])
		arr = []
		for i in range(val[0]):
			temp = input().split(' ')
			for i in range(len(temp)):
				temp[i] = int(temp[i])
			arr.append(temp)
		print(solve(arr))
	except EOFError:
		break


import sys
import math
from collections import defaultdict

def solve(test):
	(n, m) = map(int, input().split())
	mat = []
	for i in range(n):
		mat.append(list(map(int, input().split())))
	if (n + m) % 2 == 0:
		ans = 0
		idx = (n + m) // 2 - 1
		diag = [[0, 0] for i in range(n + m - 1)]
		for i in range(n):
			for j in range(m):
				if i + j != idx:
					if mat[i][j]:
						diag[i + j][1] += 1
					else:
						diag[i + j][0] += 1
		for i in range(n + m - 1):
			res1 = diag[i][0] + diag[n + m - 2 - i][0]
			res2 = diag[i][1] + diag[n + m - 2 - i][1]
			ans += min(res1, res2)
		print(ans // 2)
	else:
		ans = 0
		diag = [[0, 0] for i in range(n + m - 1)]
		for i in range(n):
			for j in range(m):
				if mat[i][j]:
					diag[i + j][1] += 1
				else:
					diag[i + j][0] += 1
		for i in range(n + m - 1):
			res1 = diag[i][0] + diag[n + m - 2 - i][0]
			res2 = diag[i][1] + diag[n + m - 2 - i][1]
			ans += min(res1, res2)
		print(ans // 2)
test_cases = int(input())
for t in range(1, test_cases + 1):
	solve(t)


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

def inar():
	return [int(el) for el in input().split()]

def main():
	t = int(input())
	for _ in range(t):
		(n, m) = inar()
		arr = []
		for i in range(n):
			ls = inar()
			arr.append(ls)
		dic = {}
		for i in range(n):
			for j in range(m):
				if i + j not in dic:
					dic[i + j] = [0, 0]
				dic[i + j][arr[i][j]] += 1
		changes = 0
		check = {}
		for (key, item) in dic.items():
			if key == m + n - 2 - key:
				continue
			if key not in check:
				zero = dic[key][0] + dic[m + n - 2 - key][0]
				one = dic[key][1] + dic[m + n - 2 - key][1]
				check[key] = 1
				check[m + n - 2 - key] = 1
				changes += min(one, zero)
		print(changes)
main()


import sys
readline = sys.stdin.readline

def solve():
	(N, M) = map(int, readline().split())
	A = [list(map(int, readline().split())) for i in range(N)]
	if N > M:
		(N, M) = (M, N)
		A = tuple(zip(*A))
	ans = 0
	for i in range(max(N, M)):
		if i >= M + N - 2 - i:
			break
		c = [0, 0]
		for j in range(min(i + 1, N)):
			n = j
			m = i - j
			c[A[n][m]] += 1
			n = N - 1 - j
			m = M - 1 - (i - j)
			c[A[n][m]] += 1
		ans += min(c)
	print(ans)
T = int(readline())
for t in range(T):
	solve()


from sys import stdin

def iinput():
	return int(stdin.readline())

def sinput():
	return input()

def minput():
	return map(int, stdin.readline().split())

def linput():
	return list(map(int, stdin.readline().split()))
t = iinput()
while t:
	t -= 1
	(n, m) = minput()
	mat = []
	for _ in range(n):
		mat.append(linput())
	g = [[] for _ in range(n + m - 1)]
	for i in range(n):
		for j in range(m):
			g[i + j].append(mat[i][j])
	b = n + m - 2
	a = 0
	ans = 0
	while a < b:
		(az, bz, ao, bo) = (g[a].count(0), g[b].count(0), g[a].count(1), g[b].count(1))
		ans += min(az + bz, ao + bo)
		a += 1
		b -= 1
	print(ans)


tt = int(input())
while tt != 0:
	(n, m) = map(int, input().split())
	list1 = list()
	for i in range(n):
		temp = list(map(int, input().split()))
		list1.append(temp)
	length = list()
	for i in range(n + m - 1):
		length.append([])
	for i in range(n):
		for j in range(m):
			length[i + j].append(list1[i][j])
	count = 0
	for i in range(len(length) // 2):
		t = length[i] + length[n + m - i - 2]
		count += min(t.count(1), t.count(0))
	print(count)
	tt -= 1


import _collections
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	a = []
	for i in range(n):
		a.append(list(map(int, input().split())))
	ans = 0
	(il, jl) = (0, 0)
	(ir, jr) = (0, 0)
	(sl, sr) = (0, n + m - 2)
	d0 = [0] * (n + m - 1)
	d1 = [0] * (n + m - 1)
	for i in range(n):
		for j in range(m):
			if a[i][j] == 1:
				d1[i + j] += 1
			else:
				d0[i + j] += 1
	for i in range((n + m - 2) // 2 + 1 - (n + m - 1) % 2):
		ans += min(2 * (d0[i] + d1[i]) - d0[n + m - 2 - i] - d0[i], 2 * (d0[i] + d1[i]) - d1[n + m - 2 - i] - d1[i])
	print(ans)


T = int(input())
for __ in range(T):
	(n, m) = map(int, input().split())
	A = []
	for __ in range(n):
		A.append(list(map(int, input().split())))
	D = [[0, 0] for __ in range(n + m - 1)]
	for i in range(n):
		for j in range(m):
			D[i + j][A[i][j]] += 1
	ans = 0
	for k1 in range((n + m - 1) // 2):
		k2 = n + m - 2 - k1
		x = min(D[k1][0] + D[k2][0], D[k1][1] + D[k2][1])
		ans += x
	print(ans)


import sys
input = sys.stdin.readline
from collections import deque, defaultdict
for T in range(int(input())):
	(n, m) = list(map(int, input().split()))
	arr = []
	for i in range(n):
		arr.append(list(map(int, input().split())))
	d = defaultdict(list)
	x = 0
	y = 0
	dq = deque()
	dq.append((x, y, 0))
	vis = [[False] * m for i in range(n)]
	while dq:
		(a, b, dist) = dq.popleft()
		vis[a][b] = True
		d[dist].append(arr[a][b])
		if a + 1 < n and vis[a + 1][b] == False:
			dq.append((a + 1, b, dist + 1))
			vis[a + 1][b] = True
		if b + 1 < m and vis[a][b + 1] == False:
			dq.append((a, b + 1, dist + 1))
			vis[a][b + 1] = True
	res = 0
	for i in range((n + m - 1) // 2):
		ci0 = d[i].count(0)
		ci1 = d[i].count(1)
		c0 = d[n + m - 2 - i].count(0)
		c1 = d[n + m - 2 - i].count(1)
		res += min(ci0 + c0, ci1 + c1)
	print(res)


t = int(input())
for i in range(t):
	(n, m) = map(int, input().split())
	sums = [0] * 61
	for row in range(n):
		l = list(map(int, input().split()))
		ones = sum(l)
		zeroes = m - ones
		for col in range(m):
			sums[row + 1 + col + 1] += l[col]
	minres = 0
	maxlen = max(n, m) + 1
	minNM = min(n, m)
	for kk in range((n + m - 1) // 2):
		k = kk + 2
		targets = min(k - 1, minNM)
		onesK = sums[k]
		zeroesK = targets - onesK
		oppozitK = n + m + 2 - k
		onesOK = sums[oppozitK]
		zeroesOK = targets - onesOK
		minres += min(onesK + onesOK, zeroesK + zeroesOK)
	print(minres)


import sys
fast_reader = sys.stdin.readline
fast_writer = sys.stdout.write

def input():
	return fast_reader().strip()

def print(*argv):
	fast_writer(' '.join((str(i) for i in argv)))
	fast_writer('\n')

def list_input():
	return list(map(int, input().split()))

def sep_input():
	return map(int, input().split())
for _ in range(int(input())):
	(n, m) = sep_input()
	l = []
	for i in range(n):
		l.append(list_input())
	d = {}
	for i in range(n):
		for j in range(m):
			try:
				d[i + j].append(l[i][j])
			except:
				d[i + j] = [l[i][j]]
	ans = 0
	for i in range((n + m - 1) // 2):
		temp = d[i] + d[n + m - 2 - i]
		ans += min(temp.count(0), temp.count(1))
	print(ans)


import sys
import math
import heapq
import collections

def inputnum():
	return int(input())

def inputnums():
	return map(int, input().split())

def inputlist():
	return list(map(int, input().split()))

def inputstring():
	return [x for x in input()]

def inputmatrixchar(rows):
	arr2d = [[j for j in input().strip()] for i in range(rows)]
	return arr2d

def inputmatrixint(rows):
	arr2d = []
	for _ in range(rows):
		arr2d.append([int(i) for i in input().split()])
	return arr2d
t = int(input())
for q in range(t):
	(n, m) = inputnums()
	a = inputmatrixint(n)
	ones = [0] * 30
	zeros = [0] * 30
	for i in range(n):
		for j in range(m):
			if i + j <= (m + n - 2) // 2:
				if a[i][j] == 0:
					zeros[i + j] += 1
				else:
					ones[i + j] += 1
			elif a[i][j] == 0:
				zeros[m + n - 2 - i - j] += 1
			else:
				ones[m + n - 2 - i - j] += 1
	ans = 0
	for i in range(30):
		if i == (m + n - 2) / 2:
			continue
		ans += min(zeros[i], ones[i])
	print(ans)