This is the hard version of the problem. The difference between the versions is in the number of possible operations that can be made. You can make hacks if and only if you solved both versions of the problem.

You are given a binary table of size n × m. This table consists of symbols 0 and 1.

You can make such operation: select 3 different cells that belong to one 2 × 2 square and change the symbols in these cells (change 0 to 1 and 1 to 0).

Your task is to make all symbols in the table equal to 0. You are allowed to make at most nm operations. You don't need to minimize the number of operations.

It can be proved, that it is always possible.

Input

The first line contains a single integer t (1 ≤ t ≤ 5000) — the number of test cases. The next lines contain descriptions of test cases.

The first line of the description of each test case contains two integers n, m (2 ≤ n, m ≤ 100).

Each of the next n lines contains a binary string of length m, describing the symbols of the next row of the table.

It is guaranteed, that the sum of nm for all test cases does not exceed 20000.

Output

For each test case print the integer k (0 ≤ k ≤ nm) — the number of operations.

In the each of the next k lines print 6 integers x_1, y_1, x_2, y_2, x_3, y_3 (1 ≤ x_1, x_2, x_3 ≤ n, 1 ≤ y_1, y_2, y_3 ≤ m) describing the next operation. This operation will be made with three cells (x_1, y_1), (x_2, y_2), (x_3, y_3). These three cells should be different. These three cells should belong to some 2 × 2 square.

Example

Input


5
2 2
10
11
3 3
011
101
110
4 4
1111
0110
0110
1111
5 5
01011
11001
00010
11011
10000
2 3
011
101


Output


1
1 1 2 1 2 2
2 
2 1 3 1 3 2
1 2 1 3 2 3
4
1 1 1 2 2 2 
1 3 1 4 2 3
3 2 4 1 4 2
3 3 4 3 4 4
4
1 2 2 1 2 2 
1 4 1 5 2 5 
4 1 4 2 5 1
4 4 4 5 3 4
2
1 3 2 2 2 3
1 2 2 1 2 2

Note

In the first test case, it is possible to make only one operation with cells (1, 1), (2, 1), (2, 2). After that, all symbols will be equal to 0.

In the second test case:

  * operation with cells (2, 1), (3, 1), (3, 2). After it the table will be: 
    
          
    011  
    001  
    000  
    

  * operation with cells (1, 2), (1, 3), (2, 3). After it the table will be: 
    
          
    000  
    000  
    000  
    




In the fifth test case:

  * operation with cells (1, 3), (2, 2), (2, 3). After it the table will be: 
    
          
    010  
    110  
    

  * operation with cells (1, 2), (2, 1), (2, 2). After it the table will be: 
    
          
    000  
    000

Difficulty: HARD
Tags: Greedy algorithms

Graph algorithms

Implementation

Constructive algorithms
Skill types: Greedy algorithms

Starter code:

Solutions:
from sys import stdin
input = stdin.readline
mp = lambda : map(int, input().split())
it = lambda : int(input())
for _ in range(it()):
	(a, b) = mp()
	t = [list(map(int, list(input().strip()))) for i in range(a)]
	saare = []
	for i in range(a - 2):
		for j in range(b):
			if t[i][j] == 1:
				if j != b - 1:
					t[i][j] = 1 - t[i][j]
					t[i + 1][j] = 1 - t[i + 1][j]
					t[i + 1][j + 1] = 1 - t[i + 1][j + 1]
					saare.append([i, j, i + 1, j, i + 1, j + 1])
				else:
					t[i][j] = 1 - t[i][j]
					t[i + 1][j] = 1 - t[i + 1][j]
					t[i + 1][j - 1] = 1 - t[i + 1][j - 1]
					saare.append([i, j, i + 1, j, i + 1, j - 1])
	ls2 = a - 2
	ls = a - 1
	for k in range(b - 2):
		if t[ls2][k] == t[ls][k] == 0:
			continue
		elif t[ls2][k] == t[ls][k] == 1:
			if t[ls2][k + 1]:
				saare.append([ls, k, ls2, k, ls2, k + 1])
				t[ls2][k] = 1 - t[ls2][k]
				t[ls][k] = 1 - t[ls][k]
				t[ls2][k + 1] = 1 - t[ls2][k + 1]
			else:
				saare.append([ls2, k, ls, k, ls, k + 1])
				t[ls2][k] = 1 - t[ls2][k]
				t[ls][k] = 1 - t[ls][k]
				t[ls][k + 1] = 1 - t[ls][k + 1]
		elif t[ls2][k] == 1:
			saare.append([ls2, k, ls2, k + 1, ls, k + 1])
			t[ls2][k] = 1 - t[ls2][k]
			t[ls2][k + 1] = 1 - t[ls2][k + 1]
			t[ls][k + 1] = 1 - t[ls][k + 1]
		else:
			saare.append([ls, k, ls, k + 1, ls2, k + 1])
			t[ls][k] = 1 - t[ls][k]
			t[ls][k + 1] = 1 - t[ls][k + 1]
			t[ls2][k + 1] = 1 - t[ls2][k + 1]
	st = str(t[ls2][b - 2]) + str(t[ls2][b - 1]) + str(t[ls][b - 2]) + str(t[ls][b - 1])
	if st == '0000':
		pass
	elif st == '0001':
		saare.append([ls, b - 2, ls, b - 1, ls2, b - 1])
		saare.append([ls, b - 1, ls2, b - 1, ls2, b - 2])
		saare.append([ls, b - 1, ls, b - 2, ls2, b - 2])
	elif st == '0010':
		saare.append([ls2, b - 2, ls, b - 2, ls, b - 1])
		saare.append([ls, b - 2, ls, b - 1, ls2, b - 1])
		saare.append([ls, b - 2, ls2, b - 2, ls2, b - 1])
	elif st == '0100':
		saare.append([ls2, b - 2, ls2, b - 1, ls, b - 1])
		saare.append([ls2, b - 1, ls, b - 1, ls, b - 2])
		saare.append([ls2, b - 1, ls2, b - 2, ls, b - 2])
	elif st == '1000':
		saare.append([ls2, b - 1, ls2, b - 2, ls, b - 2])
		saare.append([ls2, b - 2, ls, b - 2, ls, b - 1])
		saare.append([ls2, b - 2, ls2, b - 1, ls, b - 1])
	elif st == '0011':
		saare.append([ls, b - 2, ls, b - 1, ls2, b - 1])
		saare.append([ls2, b - 2, ls2, b - 1, ls, b - 1])
		saare.append([ls2, b - 1, ls, b - 1, ls, b - 2])
		saare.append([ls2, b - 1, ls2, b - 2, ls, b - 2])
	elif st == '0101':
		saare.append([ls2, b - 1, ls, b - 1, ls, b - 2])
		saare.append([ls2, b - 2, ls, b - 2, ls, b - 1])
		saare.append([ls, b - 2, ls, b - 1, ls2, b - 1])
		saare.append([ls, b - 2, ls2, b - 2, ls2, b - 1])
	elif st == '0110':
		saare.append([ls2, b - 1, ls, b - 1, ls, b - 2])
		saare.append([ls, b - 2, ls, b - 1, ls2, b - 1])
		saare.append([ls, b - 1, ls2, b - 1, ls2, b - 2])
		saare.append([ls, b - 1, ls, b - 2, ls2, b - 2])
	elif st == '0111':
		saare.append([ls2, b - 1, ls, b - 1, ls, b - 2])
	elif st == '1001':
		saare.append([ls2, b - 2, ls, b - 2, ls, b - 1])
		saare.append([ls2, b - 2, ls, b - 2, ls, b - 1])
		saare.append([ls, b - 2, ls, b - 1, ls2, b - 1])
		saare.append([ls, b - 2, ls2, b - 2, ls2, b - 1])
	elif st == '1010':
		saare.append([ls2, b - 2, ls, b - 2, ls, b - 1])
		saare.append([ls, b - 2, ls, b - 1, ls2, b - 1])
		saare.append([ls, b - 1, ls2, b - 1, ls2, b - 2])
		saare.append([ls, b - 1, ls, b - 2, ls2, b - 2])
	elif st == '1011':
		saare.append([ls2, b - 2, ls, b - 2, ls, b - 1])
	elif st == '1100':
		saare.append([ls2, b - 2, ls2, b - 1, ls, b - 1])
		saare.append([ls, b - 2, ls, b - 1, ls2, b - 1])
		saare.append([ls, b - 1, ls2, b - 1, ls2, b - 2])
		saare.append([ls, b - 1, ls, b - 2, ls2, b - 2])
	elif st == '1101':
		saare.append([ls2, b - 2, ls2, b - 1, ls, b - 1])
	elif st == '1110':
		saare.append([ls, b - 2, ls2, b - 2, ls2, b - 1])
	elif st == '1111':
		saare.append([ls, b - 2, ls2, b - 2, ls2, b - 1])
		saare.append([ls, b - 2, ls, b - 1, ls2, b - 1])
		saare.append([ls, b - 1, ls2, b - 1, ls2, b - 2])
		saare.append([ls, b - 1, ls, b - 2, ls2, b - 2])
	print(len(saare))
	for i in saare:
		print(*list(map(lambda x: x + 1, i)))


import sys
input = sys.stdin.readline
testcase = int(input())

def op(s):
	if s == '1':
		return '0'
	else:
		return '1'
for _ in range(testcase):
	(h, w) = map(int, input().split())
	grid = [list(input().rstrip()) for i in range(h)]
	ans = []
	for i in range(h - 2):
		for j in range(w):
			if grid[i][j] == '1':
				if j < w - 1:
					grid[i][j] = op(grid[i][j])
					grid[i][j + 1] = op(grid[i][j + 1])
					grid[i + 1][j] = op(grid[i + 1][j])
					ans.append((i + 1, j + 1, i + 1, j + 2, i + 2, j + 1))
				else:
					grid[i][j] = op(grid[i][j])
					grid[i + 1][j] = op(grid[i + 1][j])
					grid[i + 1][j - 1] = op(grid[i + 1][j - 1])
					ans.append((i + 1, j + 1, i + 2, j + 1, i + 2, j))
	for j in range(w - 2):
		if grid[h - 2][j] == '1':
			i = h - 2
			grid[i][j] = op(grid[i][j])
			grid[i][j + 1] = op(grid[i][j + 1])
			grid[i + 1][j] = op(grid[i + 1][j])
			ans.append((i + 1, j + 1, i + 1, j + 2, i + 2, j + 1))
		if grid[h - 1][j] == '1':
			i = h - 1
			grid[i][j] = op(grid[i][j])
			grid[i][j + 1] = op(grid[i][j + 1])
			grid[i - 1][j + 1] = op(grid[i - 1][j + 1])
			ans.append((i + 1, j + 1, i + 1, j + 2, i, j + 2))
	ls = [grid[h - 2][w - 2], grid[h - 2][w - 1], grid[h - 1][w - 2], grid[h - 1][w - 1]]
	for i in range(16):
		lsc = ls[:]
		ope = []
		for j in range(4):
			if i & 1 << j:
				ope.append(j)
		for x in ope:
			for k in range(4):
				if x != k:
					lsc[k] = op(lsc[k])
		if lsc.count('0') == 4:
			for x in ope:
				if x == 0:
					ans.append((h, w - 1, h - 1, w, h, w))
				if x == 1:
					ans.append((h - 1, w - 1, h, w - 1, h, w))
				if x == 2:
					ans.append((h - 1, w - 1, h - 1, w, h, w))
				if x == 3:
					ans.append((h - 1, w - 1, h, w - 1, h - 1, w))
			break
	print(len(ans))
	for row in ans:
		print(*row)


from sys import stdin, stdout

def solve(x, y):
	c = 0
	for i in range(x, x + 2):
		for j in range(y, y + 2):
			if s[i][j] == '1':
				c += 1
	if c == 0:
		return 1
	if c == 4 or c == 3:
		aux = []
		z = 0
		for i in range(x, x + 2):
			for j in range(y, y + 2):
				if s[i][j] == '1' and z <= 2:
					aux.append(i + 1)
					aux.append(j + 1)
					s[i][j] = '0'
					z += 1
		ans.append(aux.copy())
		return 0
	if c == 1 or c == 2:
		y1 = 0
		z = 0
		aux = []
		for i in range(x, x + 2):
			for j in range(y, y + 2):
				if s[i][j] == '1' and y1 == 0:
					aux.append(i + 1)
					aux.append(j + 1)
					s[i][j] = '0'
					y1 += 1
					continue
				if s[i][j] == '0' and z <= 1:
					aux.append(i + 1)
					aux.append(j + 1)
					s[i][j] = '1'
					z += 1
					continue
		ans.append(aux.copy())
		return 0

def clean1(x, y):
	if x + 1 == n:
		return 0
	c = 0
	aux = []
	if s[x][y + 1] == '1':
		aux.append(x + 1)
		aux.append(y + 2)
		s[x][y + 1] = '0'
		c += 1
	if s[x + 1][y + 1] == '1':
		aux.append(x + 2)
		aux.append(y + 2)
		s[x + 1][y + 1] = '0'
		c += 1
	if c == 0:
		return
	if c <= 2:
		aux.append(x + 2)
		aux.append(y + 1)
		if s[x + 1][y] == '1':
			s[x + 1][y] = '0'
		else:
			s[x + 1][y] = '1'
	if c <= 1:
		aux.append(x + 1)
		aux.append(y + 1)
		if s[x][y] == '1':
			s[x][y] = '0'
		else:
			s[x][y] = '1'
	ans.append(aux.copy())

def clean2(x, y):
	if y + 1 == m:
		return 0
	c = 0
	aux = []
	if s[x + 1][y] == '1':
		aux.append(x + 2)
		aux.append(y + 1)
		s[x + 1][y] = '0'
		c += 1
	if s[x + 1][y + 1] == '1':
		aux.append(x + 2)
		aux.append(y + 2)
		s[x + 1][y + 1] = '0'
		c += 1
	if c == 0:
		return
	if c <= 2:
		aux.append(x + 1)
		aux.append(y + 1)
		if s[x][y] == '1':
			s[x][y] = '0'
		else:
			s[x][y] = '1'
	if c <= 1:
		aux.append(x + 1)
		aux.append(y + 2)
		if s[x][y + 1] == '1':
			s[x][y + 1] = '0'
		else:
			s[x][y + 1] = '1'
	ans.append(aux.copy())
T = int(stdin.readline().strip())
for caso in range(T):
	(n, m) = map(int, stdin.readline().strip().split())
	s = [list(stdin.readline().strip()) for i in range(n)]
	ans = []
	x = n - 2
	y = m - 2
	if n % 2 != 0 and m % 2 != 0:
		q = solve(x, y)
		while q != 1:
			q = solve(x, y)
	x = n - 2
	y = m - 2
	if m % 2 != 0:
		for i in range(0, n, 2):
			clean1(i, m - 2)
	if n % 2 != 0:
		for i in range(0, m, 2):
			clean2(n - 2, i)
	for i in range(0, n - 1, 2):
		for j in range(0, m - 1, 2):
			x = solve(i, j)
			while x != 1:
				x = solve(i, j)
	stdout.write('%d\n' % len(ans))
	for i in ans:
		stdout.write('%d %d %d %d %d %d\n' % (i[0], i[1], i[2], i[3], i[4], i[5]))


import sys
input = sys.stdin.readline
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):
		s = input()
		s = s[:-1]
		op = [int(i) for i in s]
		l.append(op)
	ok = []
	for i in range(n - 1, 1, -1):
		for j in range(m - 1):
			if l[i][j] == 1:
				ok.append((i, j, i - 1, j, i - 1, j + 1))
				l[i][j] ^= 1
				l[i - 1][j] ^= 1
				l[i - 1][j + 1] ^= 1
		if l[i][m - 1] == 1:
			ok.append((i, m - 1, i - 1, m - 2, i - 1, m - 1))
			l[i][m - 1] ^= 1
			l[i - 1][m - 2] ^= 1
			l[i - 1][m - 1] ^= 1
	for j in range(m - 1, 1, -1):
		for i in range(1, n):
			if l[i][j] == 1:
				ok.append((i, j, i, j - 1, i - 1, j - 1))
				l[i][j] ^= 1
				l[i][j - 1] ^= 1
				l[i - 1][j - 1] ^= 1
		if l[0][j] == 1:
			ok.append((0, j, 0, j - 1, 1, j - 1))
			l[0][j] ^= 1
			l[0][j - 1] ^= 1
			l[1][j - 1] ^= 1
	n = 2
	m = 2
	dx = [-1, 1]
	dy = [-1, 1]
	for i in range(n):
		for j in range(m):
			if l[i][j] == 0:
				continue
			done = 0
			for p in dx:
				for q in dy:
					if i + p < n and i + p >= 0 and (j + q < m) and (j + q >= 0):
						if l[i + p][j] == 1 and l[i][j + q] == 1:
							done = 1
							l[i][j] ^= 1
							l[i + p][j] ^= 1
							l[i][j + q] ^= 1
							ok.append((i, j, i + p, j, i, j + q))
							break
				if done:
					break
	for i in range(n - 1):
		for j in range(m):
			if l[i][j] == 1 and l[i + 1][j] == 1:
				if j > 0:
					ok.append((i, j, i, j - 1, i + 1, j - 1))
					ok.append((i + 1, j, i + 1, j - 1, i, j - 1))
				else:
					ok.append((i, j, i, j + 1, i + 1, j + 1))
					ok.append((i + 1, j, i + 1, j + 1, i, j + 1))
				l[i][j] = 0
				l[i + 1][j] = 0
	for i in range(n):
		for j in range(m - 1):
			if l[i][j] == 1 and l[i][j + 1] == 1:
				if i > 0:
					ok.append((i, j, i - 1, j, i - 1, j + 1))
					ok.append((i, j + 1, i - 1, j + 1, i - 1, j))
				else:
					ok.append((i, j, i + 1, j, i + 1, j + 1))
					ok.append((i, j + 1, i + 1, j + 1, i + 1, j))
				l[i][j] = 0
				l[i][j + 1] = 0
	for i in range(n - 1):
		for j in range(m - 1):
			if l[i][j] == 1 and l[i + 1][j + 1] == 1:
				ok.append((i, j, i, j + 1, i + 1, j))
				ok.append((i + 1, j + 1, i + 1, j, i, j + 1))
				l[i][j] = 0
				l[i + 1][j + 1] = 0
	for i in range(1, n):
		for j in range(m - 1):
			if l[i][j] == 1 and l[i - 1][j + 1] == 1:
				ok.append((i, j, i, j + 1, i - 1, j))
				ok.append((i - 1, j + 1, i - 1, j, i, j + 1))
				l[i][j] = 0
				l[i - 1][j + 1] = 0
	for i in range(n - 1):
		for j in range(m - 1):
			if l[i][j] == 1:
				ok.append((i, j, i, j + 1, i + 1, j))
				ok.append((i, j, i + 1, j, i + 1, j + 1))
				ok.append((i, j, i, j + 1, i + 1, j + 1))
	for i in range(n - 1):
		if l[i][m - 1] == 1:
			ok.append((i, m - 1, i, m - 2, i + 1, m - 1))
			ok.append((i, m - 1, i, m - 2, i + 1, m - 2))
			ok.append((i, m - 1, i + 1, m - 1, i + 1, m - 2))
	for i in range(m - 1):
		if l[n - 1][i] == 1:
			ok.append((n - 1, i, n - 2, i, n - 1, i + 1))
			ok.append((n - 1, i, n - 1, i + 1, n - 2, i + 1))
			ok.append((n - 1, i, n - 2, i, n - 2, i + 1))
	if l[n - 1][m - 1] == 1:
		ok.append((n - 1, m - 1, n - 2, m - 1, n - 1, m - 2))
		ok.append((n - 1, m - 1, n - 1, m - 2, n - 2, m - 2))
		ok.append((n - 1, m - 1, n - 2, m - 1, n - 2, m - 2))
	print(len(ok))
	for i in ok:
		print(i[0] + 1, i[1] + 1, i[2] + 1, i[3] + 1, i[4] + 1, i[5] + 1)


import sys
input = sys.stdin.readline

def main():
	(n, m) = map(int, input().split())
	alst = [list(input().strip()) for _ in range(n)]
	rev = {'1': '0', '0': '1'}
	ans = []
	for i in range(n - 2):
		for j in range(m - 2):
			if alst[i][j] == '1':
				alst[i][j] = '0'
				alst[i + 1][j] = rev[alst[i + 1][j]]
				alst[i][j + 1] = rev[alst[i][j + 1]]
				ans.append((i + 1, j + 1, i + 2, j + 1, i + 1, j + 2))
	i = n - 1
	for j in range(m - 2):
		if alst[i][j] == '1' and alst[i - 1][j] == '1':
			alst[i][j] = '0'
			alst[i - 1][j] = '0'
			alst[i][j + 1] = rev[alst[i][j + 1]]
			ans.append((i + 1, j + 1, i, j + 1, i + 1, j + 2))
		elif alst[i][j] == '1':
			alst[i][j] = '0'
			alst[i - 1][j + 1] = rev[alst[i - 1][j + 1]]
			alst[i][j + 1] = rev[alst[i][j + 1]]
			ans.append((i + 1, j + 1, i, j + 2, i + 1, j + 2))
		elif alst[i - 1][j] == '1':
			alst[i - 1][j] = '0'
			alst[i - 1][j + 1] = rev[alst[i - 1][j + 1]]
			alst[i][j + 1] = rev[alst[i][j + 1]]
			ans.append((i, j + 1, i, j + 2, i + 1, j + 2))
	j = m - 1
	for i in range(n - 2):
		if alst[i][j] == '1' and alst[i][j - 1] == '1':
			alst[i][j] = '0'
			alst[i][j - 1] = '0'
			alst[i + 1][j] = rev[alst[i + 1][j]]
			ans.append((i + 1, j + 1, i + 1, j, i + 2, j + 1))
		elif alst[i][j] == '1':
			alst[i][j] = '0'
			alst[i + 1][j - 1] = rev[alst[i + 1][j - 1]]
			alst[i + 1][j] = rev[alst[i + 1][j]]
			ans.append((i + 1, j + 1, i + 2, j, i + 2, j + 1))
		elif alst[i][j - 1] == '1':
			alst[i][j - 1] = '0'
			alst[i + 1][j - 1] = rev[alst[i + 1][j - 1]]
			alst[i + 1][j] = rev[alst[i + 1][j]]
			ans.append((i + 1, j, i + 2, j, i + 2, j + 1))
	blst = [alst[-2][-2:], alst[-1][-2:]]
	cnt = 0
	one = []
	for i in range(2):
		for j in range(2):
			if blst[i][j] == '1':
				one.append((i, j))
				cnt += 1
	lst = [(0, 0), (0, 1), (1, 0), (1, 1)]
	if cnt == 0:
		pass
	if cnt == 4:
		one = [(1, 1)]
		tmp = []
		tmp.append(n - 1)
		tmp.append(m - 1)
		tmp.append(n)
		tmp.append(m - 1)
		tmp.append(n - 1)
		tmp.append(m)
		cnt = 1
		ans.append(tmp)
	if cnt == 1:
		tmp = [n - 1 + one[0][0], m - 1 + one[0][1]]
		sub = 1
		for l in lst:
			if l == one[0]:
				continue
			tmp.append(n - 1 + l[0])
			tmp.append(m - 1 + l[1])
			one.append(l)
			sub += 1
			if sub == 3:
				break
		ans.append(tmp)
		one = one[1:]
		cnt = 2
	if cnt == 2:
		tmp = [n - 1 + one[0][0], m - 1 + one[0][1]]
		for l in lst:
			if l in one:
				continue
			tmp.append(n - 1 + l[0])
			tmp.append(m - 1 + l[1])
			one.append(l)
		ans.append(tmp)
		one = one[1:]
		cnt = 3
	if cnt == 3:
		tmp = []
		for (ii, jj) in one:
			tmp.append(n - 1 + ii)
			tmp.append(m - 1 + jj)
		ans.append(tmp)
		cnt = 0
	print(len(ans))
	for row in ans:
		print(*row)
for _ in range(int(input())):
	main()


import sys
import math
from collections import deque
I = sys.stdin.readline
IN = lambda x: map(int, x.split())
L = lambda x: list(IN(x))

def two(temp0, temp1, l):
	l.append([temp1[0], temp0[1], temp0[0]])
	l.append([temp1[1], temp0[1], temp0[0]])
	return 2

def one(temp0, temp1, l):
	t1 = [temp0[0], temp0[1]]
	t0 = [temp1[0], temp0[2]]
	l.append([temp1[0], temp0[0], temp0[1]])
	return 1 + two(t0, t1, l)

def four(temp1, l):
	t0 = temp1[1:]
	l.append(t0)
	return 1 + one(t0, temp1, l)

def small(table, n, m, l):
	temp1 = []
	temp0 = []
	c = 0
	for i in range(n, n + 2):
		for j in range(m, m + 2):
			if table[i][j] == 1:
				temp1.append((i, j))
				c += 1
			else:
				temp0.append((i, j))
	if c == 0:
		return 0
	elif c == 3:
		l.append(temp1)
		return 1
	elif c == 2:
		return two(temp0, temp1, l)
	elif c == 1:
		return one(temp0, temp1, l)
	else:
		return four(temp1, l)

def threec(table, j, n, l):
	k = 0
	for i in range(0, n, 2):
		if table[i][j] == 1:
			l.append([(i, j), (i, j + 1), (i + 1, j + 1)])
			table[i][j + 1] ^= 1
			table[i + 1][j + 1] ^= 1
			k += 1
		if table[i + 1][j] == 1:
			l.append([(i + 1, j), (i, j + 1), (i + 1, j + 1)])
			table[i][j + 1] ^= 1
			table[i + 1][j + 1] ^= 1
			k += 1
		k += small(table, i, j + 1, l)
	return k

def threer(table, i, m, l):
	k = 0
	for j in range(0, m, 2):
		if table[i][j] == 1:
			l.append([(i, j), (i + 1, j + 1), (i + 1, j)])
			table[i + 1][j] ^= 1
			table[i + 1][j + 1] ^= 1
			k += 1
		if table[i][j + 1] == 1:
			l.append([(i + 1, j), (i, j + 1), (i + 1, j + 1)])
			table[i + 1][j] ^= 1
			table[i + 1][j + 1] ^= 1
			k += 1
		k += small(table, i + 1, j, l)
	return k

def helpyou(table, k, l):
	(a, b) = (table[k[0][0]][k[0][1]], table[k[1][0]][k[1][1]])
	if a == 0 and b == 0:
		return 0
	elif a == 0:
		l.append(k[1:])
		table[k[1][0]][k[1][1]] = 0
		table[k[2][0]][k[2][1]] ^= 1
		table[k[3][0]][k[3][1]] ^= 1
	elif b == 0:
		l.append([k[0], k[2], k[3]])
		table[k[2][0]][k[2][1]] ^= 1
		table[k[3][0]][k[3][1]] ^= 1
	else:
		l.append(k[:3])
		table[k[1][0]][k[1][1]] = 0
		table[k[2][0]][k[2][1]] ^= 1
	return 1

def x3(table, i, j, l):
	k = helpyou(table, [(i, j), (i + 1, j), (i, j + 1), (i + 1, j + 1)], l)
	k += helpyou(table, [(i, j + 2), (i, j + 1), (i + 1, j + 1), (i + 1, j + 2)], l)
	k += helpyou(table, [(i + 1, j + 2), (i + 2, j + 2), (i + 2, j + 1), (i + 1, j + 1)], l)
	k += small(table, i + 1, j, l)
	return k

def pikachu(table, n, m, l):
	k = 0
	for i in range(0, n, 2):
		for j in range(0, m, 2):
			k += small(table, i, j, l)
	return k
for _ in range(int(I())):
	(n, m) = IN(I())
	table = []
	for i in range(n):
		table.append(list(map(int, input())))
	l = []
	if n & 1 == 0:
		nn = n
	else:
		nn = n - 3
	if m & 1 == 0:
		mm = m
	else:
		mm = m - 3
	k = pikachu(table, nn, mm, l)
	if nn != n:
		k += threer(table, nn, mm, l)
	if mm != m:
		k += threec(table, mm, nn, l)
	if nn != n and mm != m:
		k += x3(table, nn, mm, l)
	print(k)
	for i in l:
		for j in i:
			print(j[0] + 1, j[1] + 1, end=' ')
		print()


t = int(input())

def countone(i, j):
	count = 0
	ans = []
	if arr[i][j] == '1':
		count += 1
		ans.append(i + 1)
		ans.append(j + 1)
	if arr[i + 1][j] == '1':
		count += 1
		ans.append(i + 2)
		ans.append(j + 1)
	if arr[i][j + 1] == '1':
		count += 1
		ans.append(i + 1)
		ans.append(j + 2)
	if arr[i + 1][j + 1] == '1':
		count += 1
		(ans.append(i + 2), ans.append(j + 2))
	return (ans, count)

def switch(i, j):
	if arr[i][j] == '1':
		arr[i][j] = '0'
	else:
		arr[i][j] = '1'

def change1(i, j, a):
	a1 = a.copy()
	(x1, y1) = a
	c1 = [x1 - 1, y1 - 1]
	ans1 = []
	matrix = [[i, j], [i, j + 1], [i + 1, j], [i + 1, j + 1]]
	m = []
	for item in matrix:
		if item != c1:
			m.append(item)
	for i in range(3):
		for j in range(i + 1, 3):
			k = [x1, y1, m[i][0] + 1, m[i][1] + 1, m[j][0] + 1, m[j][1] + 1]
			switch(x1 - 1, y1 - 1)
			switch(m[i][0], m[i][1])
			switch(m[j][0], m[j][1])
			ans1.append(k)
	return ans1

def change2(i, j, a1):
	a = a1.copy()
	(x1, y1, x2, y2) = a
	c1 = [x1 - 1, y1 - 1]
	c2 = [x2 - 1, y2 - 1]
	matrix = [[i, j], [i, j + 1], [i + 1, j], [i + 1, j + 1]]
	for item in matrix:
		if item != c1 and item != c2:
			a.append(item[0] + 1)
			a.append(item[1] + 1)
			switch(item[0], item[1])
			break
	switch(x1 - 1, y1 - 1)
	switch(x2 - 1, y2 - 1)
	return a
while t > 0:
	t -= 1
	(n, m) = [int(x) for x in input().split()]
	arr = []
	for i in range(n):
		s = input()
		a = []
		for j in range(m):
			a.append(s[j])
		arr.append(a)
	ans = []
	result = 0
	if n % 2 != 0:
		for i in range(m - 1):
			if arr[n - 1][i] == '1':
				switch(n - 1, i)
				switch(n - 2, i)
				switch(n - 2, i + 1)
				ans.append([n, i + 1, n - 1, i + 1, n - 1, i + 2])
				result += 1
		if arr[n - 1][m - 1] == '1':
			switch(n - 1, m - 1)
			switch(n - 2, m - 1)
			switch(n - 2, m - 2)
			ans.append([n, m, n - 1, m, n - 1, m - 1])
			result += 1
	if m % 2 != 0:
		if arr[0][m - 1] == '1':
			switch(0, m - 1)
			switch(0, m - 2)
			switch(1, m - 2)
			ans.append([1, m, 1, m - 1, 2, m - 1])
			result += 1
		end = n - n % 2
		for i in range(1, end):
			if arr[i][m - 1] == '1':
				switch(i, m - 1)
				switch(i, m - 2)
				switch(i - 1, m - 2)
				ans.append([i + 1, m, i + 1, m - 1, i, m - 1])
				result += 1
	i = 0
	j = 0
	while i < n - 1:
		while j < m - 1:
			(a, count) = countone(i, j)
			if count == 4:
				result += 4
				ans.append([i + 1, j + 2, i + 2, j + 1, i + 2, j + 2])
				switch(i, j + 1)
				switch(i + 1, j)
				switch(i + 1, j + 1)
				ans += change1(i, j, [i + 1, j + 1])
			elif count == 3:
				result += 1
				switch(a[0] - 1, a[1] - 1)
				switch(a[2] - 1, a[3] - 1)
				switch(a[4] - 1, a[5] - 1)
				ans.append(a)
			elif count == 2:
				ans.append(change2(i, j, a))
				col = ans[-1][-1]
				row = ans[-1][-2]
				ans += change1(i, j, [row, col])
				result += 4
			elif count == 1:
				ans += change1(i, j, a)
				result += 3
			j += 2
		j = 0
		i += 2
	while i < n - 1:
		while j < m - 1:
			(a, count) = countone(i, j)
			j += 1
		i += 1
	print(result)
	for i in range(result):
		print(*ans[i])


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()

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

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

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

def print_list(l):
	print(' '.join(map(str, l)))

def o():
	t = []
	if len(one) == 3:
		for (x, y) in one:
			t.append(x + 1)
			t.append(y + 1)
		res.append(t)
	elif len(one) == 4:
		for _ in range(3):
			(x, y) = one.pop()
			t.append(x + 1)
			t.append(y + 1)
			zero.append((x, y))
		res.append(t)
		o()
	elif len(one) == 1:
		tmp = one.pop()
		t.append(tmp[0] + 1)
		t.append(tmp[1] + 1)
		for _ in range(2):
			(x, y) = zero.pop()
			t.append(x + 1)
			t.append(y + 1)
			one.append((x, y))
		zero.append(tmp)
		res.append(t)
		o()
	elif len(one) == 2:
		tmp = one.pop()
		t.append(tmp[0] + 1)
		t.append(tmp[1] + 1)
		for _ in range(2):
			(x, y) = zero.pop()
			t.append(x + 1)
			t.append(y + 1)
			one.append((x, y))
		zero.append(tmp)
		res.append(t)
		o()
for _ in range(N()):
	(n, m) = RL()
	g = []
	for _ in range(n):
		g.append(list(map(int, list(input().strip()))))
	res = []
	for i in range(0, n - 2):
		for j in range(0, m - 1, 2):
			if g[i][j] == 1 and g[i][j + 1] == 1:
				res.append([i + 1, j + 1, i + 1, j + 2, i + 2, j + 1])
				g[i + 1][j] ^= 1
			elif g[i][j] == 1:
				res.append([i + 1, j + 1, i + 2, j + 2, i + 2, j + 1])
				g[i + 1][j] ^= 1
				g[i + 1][j + 1] ^= 1
			elif g[i][j + 1] == 1:
				res.append([i + 1, j + 2, i + 2, j + 2, i + 2, j + 1])
				g[i + 1][j] ^= 1
				g[i + 1][j + 1] ^= 1
		if m & 1 and g[i][m - 1] == 1:
			res.append([i + 1, m, i + 2, m, i + 2, m - 1])
			g[i + 1][-1] ^= 1
			g[i + 1][-2] ^= 1
	i = n - 2
	for j in range(m - 2):
		if g[i][j] == 1 and g[i + 1][j] == 1:
			res.append([i + 1, j + 1, i + 2, j + 1, i + 1, j + 2])
			g[i][j + 1] ^= 1
		elif g[i][j] == 1:
			res.append([i + 1, j + 1, i + 2, j + 2, i + 1, j + 2])
			g[i][j + 1] ^= 1
			g[i + 1][j + 1] ^= 1
		elif g[i + 1][j] == 1:
			res.append([i + 2, j + 1, i + 2, j + 2, i + 1, j + 2])
			g[i][j + 1] ^= 1
			g[i + 1][j + 1] ^= 1
	(one, zero) = ([], [])
	for i in range(n - 2, n):
		for j in range(m - 2, m):
			if g[i][j] == 1:
				one.append((i, j))
			else:
				zero.append((i, j))
	o()
	print(len(res))
	for l in res:
		print_list(l)


import os, sys
from io import BytesIO, IOBase
from copy import deepcopy

def solve(arr, i, j, q, n, m):
	while i < n:
		fl = 0
		if i >= n - 1:
			i = n - 2
		if j >= m - 1:
			j = m - 2
		(a, b, c, d) = ((i, j), (i + 1, j), (i, j + 1), (i + 1, j + 1))
		if j == m - 2:
			(on, ze) = ([], [])
			if arr[a[0]][a[1]] == '1':
				on.append(a)
			else:
				ze.append(a)
			if arr[b[0]][b[1]] == '1':
				on.append(b)
			else:
				ze.append(b)
			if arr[c[0]][c[1]] == '1':
				on.append(c)
			else:
				ze.append(c)
			if arr[d[0]][d[1]] == '1':
				on.append(d)
			else:
				ze.append(d)
			if len(on) == 3:
				q.append(on)
			elif len(on) == 2:
				q.append(ze + [on[0]])
				q.append(ze + [on[1]])
			elif len(on) == 1:
				q.append(on + [ze[0], ze[1]])
				q.append([on[0], ze[2], ze[1]])
				q.append([on[0], ze[2], ze[0]])
			elif len(on) == 4:
				q.append(on[:3])
				ze = on[:3]
				on = [on[-1]]
				q.append(on + [ze[0], ze[1]])
				q.append([on[0], ze[2], ze[1]])
				q.append([on[0], ze[2], ze[0]])
			arr[a[0]][a[1]] = '0'
			arr[b[0]][b[1]] = '0'
			arr[c[0]][c[1]] = '0'
			arr[d[0]][d[1]] = '0'
		else:
			fl = 1
			z = []
			if arr[i][j] == '1':
				z.append(a)
			if arr[i + 1][j] == '1':
				z.append(b)
			arr[a[0]][a[1]] = '0'
			arr[b[0]][b[1]] = '0'
			if len(z) == 1:
				z.extend([c, d])
				arr[c[0]][c[1]] = str(int(arr[c[0]][c[1]]) ^ 1)
				arr[d[0]][d[1]] = str(int(arr[d[0]][d[1]]) ^ 1)
			elif len(z) == 2:
				z.append(d)
				arr[d[0]][d[1]] = str(int(arr[d[0]][d[1]]) ^ 1)
			else:
				j += 1
				if j >= m:
					i += 2
					j = 0
				continue
			q.append(z)
		j += 2 - fl
		if j >= m:
			i += 2
			j = 0

def main():
	for _ in range(int(input())):
		(n, m) = map(int, input().split())
		arr = [list(input().strip()) for _ in range(n)]
		arr1 = deepcopy(arr)
		q = []
		(i, j) = (0, 0)
		solve(arr, i, j, q, n, m)
		if len(q) > m * n:
			arr = deepcopy(arr1)
			if m == 2:
				q = []
				(a, b, c, d) = ((n - 2, 0), (n - 2, 1), (n - 1, 0), (n - 1, 1))
				(on, ze) = ([], [])
				if arr[a[0]][a[1]] == '1':
					on.append(a)
				else:
					ze.append(a)
				if arr[b[0]][b[1]] == '1':
					on.append(b)
				else:
					ze.append(b)
				if arr[c[0]][c[1]] == '1':
					on.append(c)
				else:
					ze.append(c)
				if arr[d[0]][d[1]] == '1':
					on.append(d)
				else:
					ze.append(d)
				q.append(on)
				arr[a[0]][a[1]] = '0'
				arr[b[0]][b[1]] = '0'
				arr[c[0]][c[1]] = '0'
				arr[d[0]][d[1]] = '0'
			else:
				q = []
				(a, b, c, d) = ((0, m - 2), (0, m - 1), (1, m - 2), (1, m - 1))
				(on, ze) = ([], [])
				if arr[a[0]][a[1]] == '1':
					on.append(a)
				else:
					ze.append(a)
				if arr[b[0]][b[1]] == '1':
					on.append(b)
				else:
					ze.append(b)
				if arr[c[0]][c[1]] == '1':
					on.append(c)
				else:
					ze.append(c)
				if arr[d[0]][d[1]] == '1':
					on.append(d)
				else:
					ze.append(d)
				q.append(on)
				arr[a[0]][a[1]] = '0'
				arr[b[0]][b[1]] = '0'
				arr[c[0]][c[1]] = '0'
				arr[d[0]][d[1]] = '0'
		solve(arr, i, j, q, n, m)
		print(len(q))
		for i in q:
			print(i[0][0] + 1, i[0][1] + 1, i[1][0] + 1, i[1][1] + 1, i[2][0] + 1, i[2][1] + 1)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

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

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

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

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

class IOWrapper(IOBase):

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


import sys
input = sys.stdin.readline
t = int(input())
for tests in range(t):
	(n, m) = map(int, input().split())
	A = [list(map(int, list(input().strip()))) for i in range(n)]
	ANS = []
	for i in range(n - 2):
		for j in range(m - 1):
			if A[i][j] == 1 and A[i][j + 1] == 1:
				ANS.append((i + 1, j + 1, i + 1, j + 2, i + 2, j + 2))
				A[i][j] ^= 1
				A[i][j + 1] ^= 1
				A[i + 1][j + 1] ^= 1
			elif A[i][j] == 1 and A[i][j + 1] == 0:
				ANS.append((i + 1, j + 1, i + 2, j + 1, i + 2, j + 2))
				A[i][j] ^= 1
				A[i + 1][j] ^= 1
				A[i + 1][j + 1] ^= 1
			elif j == m - 2 and A[i][j] == 0 and (A[i][j + 1] == 1):
				ANS.append((i + 1, j + 2, i + 2, j + 1, i + 2, j + 2))
				A[i][j + 1] ^= 1
				A[i + 1][j] ^= 1
				A[i + 1][j + 1] ^= 1
	for j in range(m - 2):
		if A[n - 2][j] == 1 and A[n - 1][j] == 1:
			ANS.append((n - 1, j + 1, n, j + 1, n - 1, j + 2))
			A[n - 2][j] ^= 1
			A[n - 1][j] ^= 1
			A[n - 2][j + 1] ^= 1
		elif A[n - 2][j] == 1 and A[n - 1][j] == 0:
			ANS.append((n - 1, j + 1, n - 1, j + 2, n, j + 2))
			A[n - 2][j] ^= 1
			A[n - 2][j + 1] ^= 1
			A[n - 1][j + 1] ^= 1
		elif A[n - 2][j] == 0 and A[n - 1][j] == 1:
			ANS.append((n, j + 1, n - 1, j + 2, n, j + 2))
			A[n - 1][j] ^= 1
			A[n - 2][j + 1] ^= 1
			A[n - 1][j + 1] ^= 1
	count = 0
	C = []
	if A[n - 2][m - 2] == 1:
		count += 1
		C.append(n - 1)
		C.append(m - 1)
	if A[n - 2][m - 1] == 1:
		count += 1
		C.append(n - 1)
		C.append(m)
	if A[n - 1][m - 2] == 1:
		count += 1
		C.append(n)
		C.append(m - 1)
	if A[n - 1][m - 1] == 1:
		count += 1
		C.append(n)
		C.append(m)
	if count == 3:
		ANS.append(tuple(C))
	elif count == 0:
		True
	else:
		ANSX = []
		if count == 2:
			for (x, y) in [(n - 2, m - 2), (n - 2, m - 1), (n - 1, m - 2), (n - 1, m - 1)]:
				if A[x][y] == 0:
					C.append(x + 1)
					C.append(y + 1)
					ANSX = tuple(C)
					break
		elif count == 4:
			ANSX = (n - 1, m - 1, n - 1, m, n, m)
		if ANSX != []:
			ANS.append(ANSX)
			(a, b, c, d, e, f) = ANSX
			A[a - 1][b - 1] ^= 1
			A[c - 1][d - 1] ^= 1
			A[e - 1][f - 1] ^= 1
		if A[n - 2][m - 2] == 1:
			ANS.append((n - 1, m - 1, n - 1, m, n, m - 1))
			ANS.append((n - 1, m - 1, n - 1, m, n, m))
			ANS.append((n - 1, m - 1, n, m - 1, n, m))
		elif A[n - 1][m - 1] == 1:
			ANS.append((n, m, n - 1, m, n, m - 1))
			ANS.append((n, m, n - 1, m, n - 1, m - 1))
			ANS.append((n, m, n, m - 1, n - 1, m - 1))
		elif A[n - 2][m - 1] == 1:
			ANS.append((n - 1, m, n, m, n - 1, m - 1))
			ANS.append((n - 1, m, n, m, n, m - 1))
			ANS.append((n - 1, m, n - 1, m - 1, n, m - 1))
		elif A[n - 1][m - 2] == 1:
			ANS.append((n, m - 1, n - 1, m - 1, n, m))
			ANS.append((n, m - 1, n - 1, m - 1, n - 1, m))
			ANS.append((n, m - 1, n, m, n - 1, m))
	print(len(ANS))
	for (a, b, c, d, e, f) in ANS:
		print(a, b, c, d, e, f)


from itertools import permutations
import sys
input = lambda : sys.stdin.readline().rstrip('\r\n')

def countSet(arr):
	n = len(arr)
	m = len(arr[0])
	cnt = 0
	for i in range(n):
		for j in range(m):
			if arr[i][j] == 1:
				cnt += 1
	return cnt

def applyInPlace(grid, igrid, jgrid, sq2x2):
	if sq2x2[0][0] == 1:
		grid[igrid][jgrid] = 1 - grid[igrid][jgrid]
	if sq2x2[0][1] == 1:
		grid[igrid][jgrid + 1] = 1 - grid[igrid][jgrid + 1]
	if sq2x2[1][0] == 1:
		grid[igrid + 1][jgrid] = 1 - grid[igrid + 1][jgrid]
	if sq2x2[1][1] == 1:
		grid[igrid + 1][jgrid + 1] = 1 - grid[igrid + 1][jgrid + 1]

def solveAllExceptLast2Rows(grid):
	n = len(grid)
	m = len(grid[0])
	ans = []
	for igrid in range(n - 2):
		for jgrid in range(m):
			if grid[igrid][jgrid] == 1:
				if jgrid < m - 1:
					apply = 2
				else:
					jgrid -= 1
					apply = 3
				sq2x2 = all2x2with3set[apply]
				applyInPlace(grid, igrid, jgrid, sq2x2)
				ans.append(convertToSixIntegers(igrid, jgrid, sq2x2))
	return ans

def solveLast2Rows(grid):
	n = len(grid)
	m = len(grid[0])
	igrid = n - 2
	ans = []
	for jgrid in range(m - 2):
		if grid[igrid][jgrid] == 1 and grid[igrid + 1][jgrid] == 1:
			apply = 0
		elif grid[igrid][jgrid] == 1:
			apply = 1
		elif grid[igrid + 1][jgrid] == 1:
			apply = 3
		else:
			continue
		sq2x2 = all2x2with3set[apply]
		applyInPlace(grid, igrid, jgrid, sq2x2)
		ans.append(convertToSixIntegers(igrid, jgrid, sq2x2))
	for x in solveLastCorner(grid):
		ans.append(x)
	return ans

def solveLastCorner(grid):
	n = len(grid)
	m = len(grid[0])
	arr = [[grid[n - 2][m - 2], grid[n - 2][m - 1]], [grid[n - 1][m - 2], grid[n - 1][m - 1]]]
	if countSet(arr) == 0:
		return []
	ans = [-1, -1, -1, -1, -1]
	for p in permutations((0, 1, 2, 3)):
		arr = [[grid[n - 2][m - 2], grid[n - 2][m - 1]], [grid[n - 1][m - 2], grid[n - 1][m - 1]]]
		for i in range(4):
			applyInPlace(arr, 0, 0, all2x2with3set[p[i]])
			if countSet(arr) == 0:
				if i + 1 < len(ans):
					ans = p[:i + 1]
				break
	igrid = n - 2
	jgrid = m - 2
	ans2 = []
	for i in ans:
		sq2x2 = all2x2with3set[i]
		ans2.append(convertToSixIntegers(igrid, jgrid, sq2x2))
	return ans2

def convertToSixIntegers(igrid, jgrid, sq2x2):
	ans = []
	if sq2x2[0][0] == 1:
		ans.append(igrid + 1)
		ans.append(jgrid + 1)
	if sq2x2[0][1] == 1:
		ans.append(igrid + 1)
		ans.append(jgrid + 2)
	if sq2x2[1][0] == 1:
		ans.append(igrid + 2)
		ans.append(jgrid + 1)
	if sq2x2[1][1] == 1:
		ans.append(igrid + 2)
		ans.append(jgrid + 2)
	return ans

def multiLineArrayOfArraysPrint(arr):
	print('\n'.join([' '.join([str(x) for x in y]) for y in arr]))
all2x2sqs = []
for b in range(16):
	temp = [[0, 0], [0, 0]]
	if b & 1 << 0 > 0:
		temp[0][0] = 1
	if b & 1 << 1 > 0:
		temp[0][1] = 1
	if b & 1 << 2 > 0:
		temp[1][0] = 1
	if b & 1 << 3 > 0:
		temp[1][1] = 1
	all2x2sqs.append(temp)
all2x2with3set = []
for arr in all2x2sqs:
	if countSet(arr) == 3:
		all2x2with3set.append(arr)
t = int(input())
for _ in range(t):
	(n, m) = [int(x) for x in input().split()]
	grid = []
	for __ in range(n):
		grid.append([int(x) for x in input()])
	ans = []
	ans = ans + solveAllExceptLast2Rows(grid) + solveLast2Rows(grid)
	print(len(ans))
	multiLineArrayOfArraysPrint(ans)


import math
import random
import heapq, bisect
import sys
from collections import deque, defaultdict
from fractions import Fraction
import sys
import threading
from collections import defaultdict
threading.stack_size(10 ** 8)
mod = 10 ** 9 + 7
mod1 = 998244353
import os
import sys
from io import BytesIO, IOBase
sys.setrecursionlimit(300000)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

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

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

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

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

class IOWrapper(IOBase):

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

class TreeNode:

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

class AvlTree:

	def __init__(self):
		self._tree = None

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

class SegmentTree1:

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

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

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

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

	def __len__(self):
		return self._len

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

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

class SegmentTree:

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

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

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

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

	def __len__(self):
		return self._len

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

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

class Factorial:

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

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

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

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

class Combination:

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

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

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

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

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

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

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

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

def countGreater(arr, n, k):
	l = 0
	r = n - 1
	leftGreater = n
	while l <= r:
		m = int(l + (r - l) / 2)
		if arr[m] >= k:
			leftGreater = m
			r = m - 1
		else:
			l = m + 1
	return n - leftGreater
for ik in range(int(input())):
	(n, m) = map(int, input().split())
	l = []
	ans = []
	for i in range(n):
		l.append(list(input()))
		for j in range(m):
			l[i][j] = int(l[i][j])
	for i in range(n - 2):
		for j in range(m):
			t = 1
			if j == m - 1:
				t = -1
			if l[i][j] == 1:
				ans.append([(i, j), (i + 1, j), (i + 1, j + t)])
				l[i + 1][j] = 1 - l[i + 1][j]
				l[i + 1][j + t] = 1 - l[i + 1][j + t]
	for j in range(m - 1, 1, -1):
		if l[-2][j] == 1:
			if l[-1][j] == 1:
				ans.append([(n - 2, j), (n - 1, j), (n - 2, j - 1)])
				l[-2][j - 1] = 1 - l[-2][j - 1]
			else:
				ans.append([(n - 2, j), (n - 1, j - 1), (n - 2, j - 1)])
				l[-2][j - 1] = 1 - l[-2][j - 1]
				l[-1][j - 1] = 1 - l[-1][j - 1]
		elif l[-1][j] == 1:
			ans.append([(n - 1, j), (n - 1, j - 1), (n - 2, j - 1)])
			l[-2][j - 1] = 1 - l[-2][j - 1]
			l[-1][j - 1] = 1 - l[-1][j - 1]
	one = []
	zero = []
	for i in range(n - 2, n):
		for j in range(2):
			if l[i][j] == 1:
				one.append((i, j))
			else:
				zero.append((i, j))
	if len(one) == 3:
		ans.append(one)
	elif len(one) == 2:
		we = [one[0], zero[0], zero[1]]
		we1 = [one[1], zero[0], zero[1]]
		ans.append(we)
		ans.append(we1)
	elif len(one) == 1:
		ans.append([one[0], zero[0], zero[1]])
		t = zero[0]
		t1 = zero[1]
		zero = [zero[2], one[0]]
		one = [t, t1]
		we = [one[0], zero[0], zero[1]]
		we1 = [one[1], zero[0], zero[1]]
		ans.append(we)
		ans.append(we1)
	elif len(one) == 4:
		ans.append([one[0], one[1], one[2]])
		zero = [one[0], one[1], one[2]]
		one = [one[3]]
		ans.append([one[0], zero[0], zero[1]])
		t = zero[0]
		t1 = zero[1]
		zero = [zero[2], one[0]]
		one = [t, t1]
		we = [one[0], zero[0], zero[1]]
		we1 = [one[1], zero[0], zero[1]]
		ans.append(we)
		ans.append(we1)
	print(len(ans))
	for i in range(len(ans)):
		for j in range(3):
			print(ans[i][j][0] + 1, ans[i][j][1] + 1, end=' ')
		print()


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 main():
	for _ in range(int(input())):
		(n, m) = [int(x) for x in input().split()]
		t = [[int(x) for x in input()] for i in range(n)]
		ans = []

		def op(a, b, c):
			t[a[0]][a[1]] ^= 1
			t[b[0]][b[1]] ^= 1
			t[c[0]][c[1]] ^= 1
			ans.append([a[0] + 1, a[1] + 1, b[0] + 1, b[1] + 1, c[0] + 1, c[1] + 1])
		for i in range(n - 1, 1, -1):
			for j in range(m):
				if t[i][j]:
					if j + 1 < m:
						op((i, j), (i - 1, j), (i - 1, j + 1))
					else:
						op((i, j), (i - 1, j), (i - 1, j - 1))
		for j in range(m - 1, 1, -1):
			for i in range(2):
				if t[i][j]:
					op((i, j), (0, j - 1), (1, j - 1))
		for i in range(2):
			for j in range(2):
				tot = t[0][0] + t[0][1] + t[1][0] + t[1][1]
				if (tot + t[i][j]) % 2:
					op((1 - i, j), (1 - i, 1 - j), (i, 1 - j))
		print(len(ans))
		for op in ans:
			print(*op)
main()


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

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

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

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

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

def BI():
	return sys.stdin.buffer.readline().rstrip()

def SI():
	return sys.stdin.buffer.readline().rstrip().decode()

def flip(i, j):
	res = []
	if j == w - 1:
		j -= 1
	cnt = 3
	if aa[i][j]:
		aa[i][j] ^= 1
		cnt -= 1
		res += [i + 1, j + 1]
	if aa[i][j + 1]:
		aa[i][j + 1] ^= 1
		cnt -= 1
		res += [i + 1, j + 2]
	if cnt == 2 or aa[i + 1][j]:
		aa[i + 1][j] ^= 1
		cnt -= 1
		res += [i + 2, j + 1]
	if cnt:
		aa[i + 1][j + 1] ^= 1
		cnt -= 1
		res += [i + 2, j + 2]
	return res

def right(i, j):
	res = []
	cnt = 3
	if aa[i][j]:
		aa[i][j] ^= 1
		cnt -= 1
		res += [i + 1, j + 1]
	if aa[i + 1][j]:
		aa[i + 1][j] ^= 1
		cnt -= 1
		res += [i + 2, j + 1]
	if cnt == 2 or aa[i][j + 1]:
		aa[i][j + 1] ^= 1
		cnt -= 1
		res += [i + 1, j + 2]
	if cnt:
		aa[i + 1][j + 1] ^= 1
		res += [i + 2, j + 2]
	return res

def zero(sj):
	ij1 = []
	ij0 = []
	res = []
	for i in range(h - 2, h):
		for j in range(sj, sj + 2):
			if aa[i][j]:
				ij1.append((i, j))
			else:
				ij0.append((i, j))
	if len(ij1) == 3:
		for (i, j) in ij1:
			aa[i][j] ^= 1
			res += [i + 1, j + 1]
	elif len(ij1) == 2:
		(i, j) = ij1[0]
		aa[i][j] ^= 1
		res += [i + 1, j + 1]
		for (i, j) in ij0:
			aa[i][j] ^= 1
			res += [i + 1, j + 1]
	else:
		(i, j) = ij1[0]
		aa[i][j] ^= 1
		res += [i + 1, j + 1]
		for (i, j) in ij0[:2]:
			aa[i][j] ^= 1
			res += [i + 1, j + 1]
	return res
for _ in range(II()):
	(h, w) = MI()
	aa = [[int(c) for c in SI()] for _ in range(h)]
	ans = []
	for i in range(h - 2):
		for j in range(w):
			if aa[i][j]:
				ans.append(flip(i, j))
	for j in range(w - 1):
		if aa[h - 2][j] + aa[h - 1][j]:
			ans.append(right(h - 2, j))
	while aa[h - 2][w - 2] + aa[h - 2][w - 1] + aa[h - 1][w - 2] + aa[h - 1][w - 1]:
		ans.append(zero(w - 2))
	print(len(ans))
	for row in ans:
		print(*row)


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

def solve(sq, x, y):
	s = sum((sum(i) for i in sq))
	v = [(x, y, x + 1, y, x, y + 1), (x, y, x + 1, y + 1, x, y + 1), (x, y, x + 1, y, x + 1, y + 1), (x + 1, y + 1, x + 1, y, x, y + 1)]
	if s > 3:
		return v
	if s > 2:
		if sq[0][0] < 1:
			return [v[3]]
		if sq[0][1] < 1:
			return [v[2]]
		if sq[1][0] < 1:
			return [v[1]]
		return [v[0]]
	if s > 1:
		if sq[0][0] < 1 and sq[0][1] < 1:
			return v[:2]
		if sq[0][0] < 1 and sq[1][1] < 1:
			return v[1:3]
		if sq[0][0] < 1 and sq[1][0] < 1:
			return [v[0], v[2]]
		if sq[0][1] < 1 and sq[1][1] < 1:
			return [v[1], v[3]]
		if sq[0][1] < 1 and sq[1][0] < 1:
			return [v[0], v[3]]
		if sq[1][0] < 1 and sq[1][1] < 1:
			return v[2:]
	if s:
		if sq[0][0]:
			k = 3
		elif sq[0][1]:
			k = 2
		elif sq[1][0]:
			k = 1
		else:
			k = 0
		return v[:k] + v[k + 1:]
	return []
O = []
for _ in range(int(Z())):
	(n, m) = map(int, Z().split())
	a = []
	o = []
	for i in range(n):
		a.append(list(map(lambda x: x % 2, Z().strip())))
	if n % 2:
		for y in range(m // 2):
			i = y * 2
			if a[-1][i]:
				if a[-1][i + 1]:
					o += [(n, i + 1, n, i + 2, n - 1, i + 1)]
					a[-2][i] = 1 - a[-2][i]
				else:
					o += [(n, i + 1, n - 1, i + 2, n - 1, i + 1)]
					a[-2][i] = 1 - a[-2][i]
					a[-2][i + 1] = 1 - a[-2][i + 1]
			elif a[-1][i + 1]:
				o += [(n, i + 2, n - 1, i + 2, n - 1, i + 1)]
				a[-2][i] = 1 - a[-2][i]
				a[-2][i + 1] = 1 - a[-2][i + 1]
		if m % 2 and a[-1][-1]:
			o += [(n, m, n - 1, m, n - 1, m - 1)]
			a[-2][-1] = 1 - a[-2][-1]
			a[-2][-2] = 1 - a[-2][-2]
	if m % 2:
		for x in range(n // 2):
			i = x * 2
			if a[i][-1]:
				if a[i + 1][-1]:
					o += [(i + 1, m, i + 2, m, i + 1, m - 1)]
					a[i][-2] = 1 - a[i][-2]
				else:
					o += [(i + 1, m, i + 2, m - 1, i + 1, m - 1)]
					a[i][-2] = 1 - a[i][-2]
					a[i + 1][-2] = 1 - a[i + 1][-2]
			elif a[i + 1][-1]:
				o += [(i + 2, m - 1, i + 2, m, i + 1, m - 1)]
				a[i][-2] = 1 - a[i][-2]
				a[i + 1][-2] = 1 - a[i + 1][-2]
	for i in range(n // 2):
		for j in range(m // 2):
			(x, y) = (2 * i, 2 * j)
			o += solve(((a[x][y], a[x][y + 1]), (a[x + 1][y], a[x + 1][y + 1])), x + 1, y + 1)
	O.append(str(len(o)))
	O.append('\n'.join((' '.join(map(str, i)) for i in o)))
print('\n'.join(O))


import sys
Z = sys.stdin.readline
O = []

def S(q, x, y):
	s = sum((sum(i) for i in q))
	v = [(x, y, x + 1, y, x, y + 1), (x, y, x + 1, y + 1, x, y + 1), (x, y, x + 1, y, x + 1, y + 1), (x + 1, y + 1, x + 1, y, x, y + 1)]
	if s > 3:
		return v
	if s > 2:
		if q[0][0] < 1:
			return [v[3]]
		if q[0][1] < 1:
			return [v[2]]
		if q[1][0] < 1:
			return [v[1]]
		return [v[0]]
	if s > 1:
		if q[0][0] < 1 and q[0][1] < 1:
			return v[:2]
		if q[0][0] < 1 and q[1][1] < 1:
			return v[1:3]
		if q[0][0] < 1 and q[1][0] < 1:
			return [v[0], v[2]]
		if q[0][1] < 1 and q[1][1] < 1:
			return [v[1], v[3]]
		if q[0][1] < 1 and q[1][0] < 1:
			return [v[0], v[3]]
		if q[1][0] < 1 and q[1][1] < 1:
			return v[2:]
	if s:
		if q[0][0]:
			k = 3
		elif q[0][1]:
			k = 2
		elif q[1][0]:
			k = 1
		else:
			k = 0
		return v[:k] + v[k + 1:]
	return []
for _ in range(int(Z())):
	(n, m) = map(int, Z().split())
	a = []
	o = []
	for i in range(n):
		a.append(list(map(int, Z().strip())))
	if n % 2:
		for i in range(0, m - m % 2, 2):
			if a[-1][i]:
				if a[-1][i + 1]:
					o += [(n, i + 1, n, i + 2, n - 1, i + 1)]
					a[-2][i] = 1 - a[-2][i]
				else:
					o += [(n, i + 1, n - 1, i + 2, n - 1, i + 1)]
					a[-2][i] = 1 - a[-2][i]
					a[-2][i + 1] = 1 - a[-2][i + 1]
			elif a[-1][i + 1]:
				o += [(n, i + 2, n - 1, i + 2, n - 1, i + 1)]
				a[-2][i] = 1 - a[-2][i]
				a[-2][i + 1] = 1 - a[-2][i + 1]
		if m % 2 and a[-1][-1]:
			o += [(n, m, n - 1, m, n - 1, m - 1)]
			a[-2][-1] = 1 - a[-2][-1]
			a[-2][-2] = 1 - a[-2][-2]
	if m % 2:
		for i in range(0, n - n % 2, 2):
			if a[i][-1]:
				if a[i + 1][-1]:
					o += [(i + 1, m, i + 2, m, i + 1, m - 1)]
					a[i][-2] = 1 - a[i][-2]
				else:
					o += [(i + 1, m, i + 2, m - 1, i + 1, m - 1)]
					a[i][-2] = 1 - a[i][-2]
					a[i + 1][-2] = 1 - a[i + 1][-2]
			elif a[i + 1][-1]:
				o += [(i + 2, m - 1, i + 2, m, i + 1, m - 1)]
				a[i][-2] = 1 - a[i][-2]
				a[i + 1][-2] = 1 - a[i + 1][-2]
	for i in range(n // 2):
		for j in range(m // 2):
			(x, y) = (2 * i, 2 * j)
			o += S(((a[x][y], a[x][y + 1]), (a[x + 1][y], a[x + 1][y + 1])), x + 1, y + 1)
	O.append(str(len(o)))
	O.append('\n'.join((' '.join(map(str, i)) for i in o)))
print('\n'.join(O))


from sys import stdin

def c(x1, y1, x2, y2, x3, y3):
	ans.append((x1 + 1, y1 + 1, x2 + 1, y2 + 1, x3 + 1, y3 + 1))
	a[x1][y1] ^= 1
	a[x2][y2] ^= 1
	a[x3][y3] ^= 1
	return
tt = int(stdin.readline())
for loop in range(tt):
	(n, m) = map(int, stdin.readline().split())
	a = []
	ans = []
	for i in range(n):
		tmp = list(map(int, list(stdin.readline()[:-1])))
		a.append(tmp)
	for i in range(n - 2):
		for j in range(m):
			if j != m - 1:
				if a[i][j] == 1 and a[i][j + 1] == 1:
					if a[i + 1][j] == 1:
						c(i, j, i, j + 1, i + 1, j)
					else:
						c(i, j, i, j + 1, i + 1, j + 1)
				elif a[i][j] == 1:
					c(i, j, i + 1, j, i + 1, j + 1)
				else:
					continue
			elif a[i][j] == 1:
				c(i, j, i + 1, j, i + 1, j - 1)
	for i in range(n - 2, n - 1):
		for j in range(m - 1):
			if a[i][j] == 1 and a[i + 1][j] == 1:
				if a[i][j + 1] == 1:
					c(i, j, i + 1, j, i, j + 1)
				else:
					c(i, j, i + 1, j, i + 1, j + 1)
			elif a[i][j] == 1:
				c(i, j, i, j + 1, i + 1, j + 1)
			elif a[i + 1][j] == 1:
				c(i + 1, j, i, j + 1, i + 1, j + 1)
			else:
				continue
	if a[n - 1][m - 1] == 0 and a[n - 2][m - 1] == 0:
		pass
	elif a[n - 1][m - 1] == 1 and a[n - 2][m - 1] == 0:
		c(n - 1, m - 1, n - 2, m - 1, n - 2, m - 2)
		c(n - 1, m - 1, n - 1, m - 2, n - 2, m - 2)
		c(n - 1, m - 1, n - 1, m - 2, n - 2, m - 1)
	elif a[n - 1][m - 1] == 0 and a[n - 2][m - 1] == 1:
		c(n - 1, m - 1, n - 1, m - 2, n - 2, m - 1)
		c(n - 1, m - 1, n - 2, m - 1, n - 2, m - 2)
		c(n - 2, m - 2, n - 1, m - 2, n - 2, m - 1)
	else:
		c(n - 1, m - 1, n - 1, m - 2, n - 2, m - 2)
		c(n - 2, m - 2, n - 1, m - 2, n - 2, m - 1)
	print(len(ans))
	for i in ans:
		print(*i)


import sys
input = sys.stdin.readline
t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	table = [list(map(int, list(input().strip()))) for _ in range(n)]

	def add(a, b, c):
		table[a[0]][a[1]] = 1 - table[a[0]][a[1]]
		table[b[0]][b[1]] = 1 - table[b[0]][b[1]]
		table[c[0]][c[1]] = 1 - table[c[0]][c[1]]
		out.append(' '.join(map(lambda x: str(x + 1), (a[0], a[1], b[0], b[1], c[0], c[1]))))
	out = []
	for i in range(n - 1, 1, -1):
		for j in range(m):
			if table[i][j]:
				if j + 1 < m:
					add((i, j), (i - 1, j), (i - 1, j + 1))
				else:
					add((i, j), (i - 1, j), (i - 1, j - 1))
	for j in range(m - 1, 1, -1):
		for i in range(2):
			if table[i][j]:
				if table[i][j]:
					add((i, j), (0, j - 1), (1, j - 1))
	for i in range(2):
		for j in range(2):
			tot = table[0][0] + table[0][1] + table[1][0] + table[1][1]
			if (tot + table[i][j]) % 2:
				add((1 - i, j), (1 - i, 1 - j), (i, 1 - j))
	print(len(out))
	print('\n'.join(out))


import sys
readline = sys.stdin.readline
T = int(readline())
Ans = []
for qu in range(T):
	(N, M) = map(int, readline().split())
	ans = []
	G = [list(map(int, readline().strip())) for _ in range(N)]
	for i in range(N - 2):
		for j in range(M - 1):
			if G[i][j]:
				ans.append(f'{i + 1} {j + 1} {i + 1} {j + 2} {i + 2} {j + 1}')
				G[i][j] ^= 1
				G[i][j + 1] ^= 1
				G[i + 1][j] ^= 1
		j = M - 1
		if G[i][M - 1]:
			ans.append(f'{i + 1} {j + 1} {i + 2} {j} {i + 2} {j + 1}')
			G[i][j] ^= 1
			G[i + 1][j - 1] ^= 1
			G[i + 1][j] ^= 1
	i = N - 2
	for j in range(M - 2):
		if G[i][j]:
			ans.append(f'{i + 1} {j + 1} {i + 1} {j + 2} {i + 2} {j + 1}')
			G[i][j] ^= 1
			G[i][j + 1] ^= 1
			G[i + 1][j] ^= 1
	a = N - 2
	b = N - 1
	ai = a + 1
	bi = b + 1
	for j in range(M - 2):
		if G[a][j] and G[b][j]:
			ans.append(f'{ai} {j + 1} {bi} {j + 1} {ai} {j + 2}')
			G[a][j] ^= 1
			G[b][j] ^= 1
			G[a][j + 1] ^= 1
			continue
		if G[a][j] or G[b][j]:
			if G[a][j]:
				c = a
			else:
				c = b
			ans.append(f'{c + 1} {j + 1} {bi} {j + 2} {ai} {j + 2}')
			G[c][j] ^= 1
			G[b][j + 1] ^= 1
			G[a][j + 1] ^= 1
	H = [G[N - 2][M - 2], G[N - 1][M - 2], G[N - 2][M - 1], G[N - 1][M - 1]]
	(ax, ay) = (N - 2 + 1, M - 2 + 1)
	(bx, by) = (N - 1 + 1, M - 2 + 1)
	(cx, cy) = (N - 2 + 1, M - 1 + 1)
	(dx, dy) = (N - 1 + 1, M - 1 + 1)
	abcd = [(ax, ay), (bx, by), (cx, cy), (dx, dy)]
	if H.count(1) == 4:
		H[0] ^= 1
		H[1] ^= 1
		H[2] ^= 1
		ans.append(f'{ax} {ay} {bx} {by} {cx} {cy}')
	if H.count(1) == 1:
		res = [0, 1, 2, 3]
		for idx in range(4):
			if H[idx]:
				break
		res.remove(res[idx - 1])
		ans.append(f'{abcd[res[0]][0]} {abcd[res[0]][1]} {abcd[res[1]][0]} {abcd[res[1]][1]} {abcd[res[2]][0]} {abcd[res[2]][1]}')
		for r in res:
			H[r] ^= 1
	if H.count(1) == 2:
		res = []
		for idx in range(4):
			if not H[idx]:
				res.append(idx)
		for idx in range(4):
			if H[idx]:
				res.append(idx)
				break
		ans.append(f'{abcd[res[0]][0]} {abcd[res[0]][1]} {abcd[res[1]][0]} {abcd[res[1]][1]} {abcd[res[2]][0]} {abcd[res[2]][1]}')
		for r in res:
			H[r] ^= 1
	if H.count(1) == 3:
		res = []
		for idx in range(4):
			if H[idx]:
				res.append(idx)
		ans.append(f'{abcd[res[0]][0]} {abcd[res[0]][1]} {abcd[res[1]][0]} {abcd[res[1]][1]} {abcd[res[2]][0]} {abcd[res[2]][1]}')
		for r in res:
			H[r] ^= 1
	Ans.append(str(len(ans)))
	Ans.extend(ans)
print('\n'.join(Ans))


t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	a = [list(map(int, input())) for i in range(n)]

	def add(x, y, z):
		a[x[0]][x[1]] ^= 1
		a[y[0]][y[1]] ^= 1
		a[z[0]][z[1]] ^= 1
		ans.append(' '.join(map(lambda x: str(x + 1), (*x, *y, *z))))
	ans = []
	for i in range(n - 1, 1, -1):
		for j in range(m):
			if a[i][j]:
				add((i, j), (i - 1, j), (i - 1, j + (1 if j < m - 1 else -1)))
	for j in range(m - 1, 1, -1):
		for i in (0, 1):
			if a[i][j]:
				add((i, j), (0, j - 1), (1, j - 1))
	for i in (0, 1):
		for j in (0, 1):
			if (a[0][0] + a[0][1] + a[1][0] + a[1][1] + a[i][j]) % 2:
				add((i ^ 1, j), (i, j ^ 1), (i ^ 1, j ^ 1))
	print(len(ans))
	print('\n'.join(ans))


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 solve(area, ans, n, m):
	if n % 2 == 1:
		n -= 1
	if m % 2 == 1:
		m -= 1
	for q in range(0, n, 2):
		for r in range(0, m, 2):
			g1 = [area[q][r], q + 1, r + 1]
			g2 = [area[q + 1][r], q + 2, r + 1]
			g3 = [area[q][r + 1], q + 1, r + 2]
			g4 = [area[q + 1][r + 1], q + 2, r + 2]
			ass = [g1, g2, g3, g4]
			ass.sort()
			cnt = 0
			for i in range(len(ass)):
				if ass[i][0] == 1:
					cnt += 1
			if cnt == 4:
				t1 = []
				t1.extend([ass[0][1], ass[0][2]])
				t1.extend([ass[1][1], ass[1][2]])
				t1.extend([ass[2][1], ass[2][2]])
				for i in range(3):
					ass[i][0] = 0
				ans.append(t1)
				t1 = []
				cnt = 1
			if cnt == 3:
				t1 = []
				for i in range(len(ass)):
					if ass[i][0] == 1:
						t1.extend([ass[i][1], ass[i][2]])
				ans.append(t1)
				continue
				cnt = 1
			if cnt == 2:
				t1 = []
				for i in range(len(ass)):
					if ass[i][0] == 0:
						t1.extend([ass[i][1], ass[i][2]])
						ass[i][0] = -1
				for i in range(len(ass)):
					if ass[i][0] == 1:
						t1.extend([ass[i][1], ass[i][2]])
						ass[i][0] = 0
						break
				ans.append(t1)
				t1 = []
				for i in range(len(ass)):
					if abs(ass[i][0]) == 1:
						t1.extend([ass[i][1], ass[i][2]])
				ans.append(t1)
				continue
			if cnt == 1:
				t1 = []
				for i in range(len(ass)):
					if ass[i][0] == 0:
						t1.extend([ass[i][1], ass[i][2]])
						ass[i][0] = -1
					if len(t1) == 4:
						break
				for i in range(len(ass)):
					if ass[i][0] == 1:
						t1.extend([ass[i][1], ass[i][2]])
						ass[i][0] = 0
						break
				for i in range(len(ass)):
					ass[i][0] = abs(ass[i][0])
				ans.append(t1)
				cnt = 2
			if cnt == 2:
				t1 = []
				for i in range(len(ass)):
					if ass[i][0] == 0:
						t1.extend([ass[i][1], ass[i][2]])
						ass[i][0] = -1
				for i in range(len(ass)):
					if ass[i][0] == 1:
						t1.extend([ass[i][1], ass[i][2]])
						ass[i][0] = 0
						break
				ans.append(t1)
				t1 = []
				for i in range(len(ass)):
					if abs(ass[i][0]) == 1:
						t1.extend([ass[i][1], ass[i][2]])
				ans.append(t1)
				continue
a = int(input())
for i in range(a):
	(n, m) = map(int, input().split())
	ans = []
	area = []
	for i in range(n):
		s = input()
		g1 = []
		for j in range(len(s)):
			g1.append(int(s[j]))
		area.append(g1)
	if n % 2 == 0 and m % 2 == 0:
		solve(area, ans, n, m)
		print(len(ans))
		for j in range(len(ans)):
			print(*ans[j])
		continue
	if m % 2 == 1:
		ans = []
		for j in range(n):
			if area[j][m - 1] == 1:
				area[j][m - 1] = 0
				t1 = []
				t1.extend([j + 1, m])
				t1.extend([j + 1, m - 1])
				area[j][m - 2] = 1 - area[j][m - 2]
				if j - 1 >= 0:
					area[j - 1][m - 2] = 1 - area[j - 1][m - 2]
					t1.extend([j, m - 1])
				else:
					area[j + 1][m - 2] = 1 - area[j + 1][m - 2]
					t1.extend([j + 2, m - 1])
				ans.append(t1)
		if n % 2 == 0:
			solve(area, ans, n, m)
			print(len(ans))
			for j in range(len(ans)):
				print(*ans[j])
	if n % 2 == 1:
		for j in range(m):
			if area[n - 1][j] == 1:
				t1 = []
				area[n - 1][j] = 0
				t1.extend([n, j + 1])
				t1.extend([n - 1, j + 1])
				area[n - 2][j] = 1 - area[n - 2][j]
				if j - 1 >= 0:
					area[n - 2][j - 1] = 1 - area[n - 2][j - 1]
					t1.extend([n - 1, j])
				else:
					area[n - 2][j + 1] = 1 - area[n - 2][j + 1]
					t1.extend([n - 1, j + 2])
				ans.append(t1)
		solve(area, ans, n, m)
		print(len(ans))
		for j in range(len(ans)):
			print(*ans[j])


(s, res) = ([], [])

def solve1(x, y, c1, c2, c3, c4):
	if c1 == '1':
		res.append([x, y, x, y + 1, x + 1, y])
		solve2(x, y, '0', '1', '1', '0')
	elif c2 == '1':
		res.append([x, y, x, y + 1, x + 1, y])
		solve2(x, y, '1', '0', '1', '0')
	elif c3 == '1':
		res.append([x, y, x, y + 1, x + 1, y])
		solve2(x, y, '1', '1', '0', '0')
	elif c4 == '1':
		res.append([x, y, x, y + 1, x + 1, y + 1])
		solve2(x, y, '1', '1', '0', '0')

def solve2(x, y, c1, c2, c3, c4):
	if c1 == '0' and c2 == '0':
		res.append([x, y, x, y + 1, x + 1, y])
		solve3(x, y, '1', '1', '0', '1')
	elif c1 == '0' and c3 == '0':
		res.append([x, y, x + 1, y, x, y + 1])
		solve3(x, y, '1', '0', '1', '1')
	elif c1 == '0' and c4 == '0':
		res.append([x, y, x + 1, y, x + 1, y + 1])
		solve3(x, y, '1', '1', '0', '1')
	elif c2 == '0' and c3 == '0':
		res.append([x, y, x + 1, y, x, y + 1])
		solve3(x, y, '0', '1', '1', '1')
	elif c2 == '0' and c4 == '0':
		res.append([x, y, x, y + 1, x + 1, y + 1])
		solve3(x, y, '0', '1', '1', '1')
	elif c3 == '0' and c4 == '0':
		res.append([x, y, x + 1, y, x + 1, y + 1])
		solve3(x, y, '0', '1', '1', '1')

def solve3(x, y, c1, c2, c3, c4):
	if c1 == '0':
		res.append([x + 1, y, x, y + 1, x + 1, y + 1])
	elif c2 == '0':
		res.append([x + 1, y, x, y, x + 1, y + 1])
	elif c3 == '0':
		res.append([x, y, x, y + 1, x + 1, y + 1])
	elif c4 == '0':
		res.append([x + 1, y, x, y + 1, x, y])

def solve4(x, y):
	res.append([x, y, x, y + 1, x + 1, y])
	solve1(x, y, '0', '0', '0', '1')

def trans(x1, y1, x2, y2, x3, y3):
	s[x1][y1] = '1' if s[x1][y1] == '0' else '0'
	s[x2][y2] = '1' if s[x2][y2] == '0' else '0'
	s[x3][y3] = '1' if s[x3][y3] == '0' else '0'
	res.append([x1 + 1, y1 + 1, x2 + 1, y2 + 1, x3 + 1, y3 + 1])
T = int(input())
for _ in range(T):
	(n, m) = map(int, input().split())
	s.clear()
	res.clear()
	for i in range(n):
		s.append(list(input()))
	if m % 2:
		for i in range(n - 1):
			if s[i][m - 1] == '1' and s[i + 1][m - 1] == '0':
				trans(i, m - 1, i, m - 2, i + 1, m - 2)
			elif s[i][m - 1] == '0' and s[i + 1][m - 1] == '1':
				trans(i + 1, m - 1, i, m - 2, i + 1, m - 2)
			elif s[i][m - 1] == '1' and s[i + 1][m - 1] == '1':
				trans(i + 1, m - 1, i, m - 1, i + 1, m - 2)
	for j in range(0, m - 1, 2):
		if n % 2:
			if s[n - 1][j] == '1' and s[n - 1][j + 1] == '0':
				trans(n - 1, j, n - 2, j, n - 2, j + 1)
			elif s[n - 1][j] == '0' and s[n - 1][j + 1] == '1':
				trans(n - 1, j + 1, n - 2, j, n - 2, j + 1)
			elif s[n - 1][j] == '1' and s[n - 1][j + 1] == '1':
				trans(n - 1, j, n - 2, j, n - 1, j + 1)
		for i in range(0, n - 1, 2):
			num = 0
			if s[i][j] == '1':
				num += 1
			if s[i][j + 1] == '1':
				num += 1
			if s[i + 1][j] == '1':
				num += 1
			if s[i + 1][j + 1] == '1':
				num += 1
			if num == 1:
				solve1(i + 1, j + 1, s[i][j], s[i][j + 1], s[i + 1][j], s[i + 1][j + 1])
			if num == 2:
				solve2(i + 1, j + 1, s[i][j], s[i][j + 1], s[i + 1][j], s[i + 1][j + 1])
			if num == 3:
				solve3(i + 1, j + 1, s[i][j], s[i][j + 1], s[i + 1][j], s[i + 1][j + 1])
			if num == 4:
				solve4(i + 1, j + 1)
	print(len(res))
	for arr in res:
		print(' '.join(('%s' % d for d in arr)))


def flip(x, y):
	global mat
	if mat[x][y]:
		mat[x][y] = 0
	else:
		mat[x][y] = 1

def func(x1, y1, x2, y2):
	global mat, k
	(ones, z) = ([], [])
	if mat[x1][y1] == 1:
		ones.append((x1 + 1, y1 + 1))
	else:
		z.append((x1 + 1, y1 + 1))
	if mat[x2][y1] == 1:
		ones.append((x2 + 1, y1 + 1))
	else:
		z.append((x2 + 1, y1 + 1))
	if mat[x1][y2] == 1:
		ones.append((x1 + 1, y2 + 1))
	else:
		z.append((x1 + 1, y2 + 1))
	if mat[x2][y2] == 1:
		ones.append((x2 + 1, y2 + 1))
	else:
		z.append((x2 + 1, y2 + 1))
	while len(ones) != 0:
		if len(ones) == 4:
			k += 1
			t = []
			for (x, y) in ones[:-1]:
				mat[x - 1][y - 1] = 0
				t.append(x)
				t.append(y)
			out.append(t)
		elif len(ones) == 3:
			k += 1
			t = []
			for (x, y) in ones:
				mat[x - 1][y - 1] = 0
				t.append(x)
				t.append(y)
			out.append(t)
		elif len(ones) == 2:
			k += 1
			t = []
			for (x, y) in ones[:-1]:
				mat[x - 1][y - 1] = 0
				t.append(x)
				t.append(y)
			for (x, y) in z:
				mat[x - 1][y - 1] = 1
				t.append(x)
				t.append(y)
			out.append(t)
		else:
			k += 1
			t = []
			for (x, y) in ones:
				mat[x - 1][y - 1] = 0
				t.append(x)
				t.append(y)
			for (x, y) in z[:-1]:
				mat[x - 1][y - 1] = 1
				t.append(x)
				t.append(y)
			out.append(t)
		(ones, z) = ([], [])
		if mat[x1][y1] == 1:
			ones.append((x1 + 1, y1 + 1))
		else:
			z.append((x1 + 1, y1 + 1))
		if mat[x2][y1] == 1:
			ones.append((x2 + 1, y1 + 1))
		else:
			z.append((x2 + 1, y1 + 1))
		if mat[x1][y2] == 1:
			ones.append((x1 + 1, y2 + 1))
		else:
			z.append((x1 + 1, y2 + 1))
		if mat[x2][y2] == 1:
			ones.append((x2 + 1, y2 + 1))
		else:
			z.append((x2 + 1, y2 + 1))
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	mat = []
	for i in range(n):
		mat.append(list(map(int, list(input()))))
	k = 0
	out = []
	i = 0
	if n % 2:
		j = 0
		if m % 2:
			func(n - 2, m - 2, n - 1, m - 1)
		while j < m - 1:
			if mat[n - 1][j] == 1:
				flip(n - 1, j)
				flip(n - 2, j)
				flip(n - 2, j + 1)
				k += 1
				out.append([n, j + 1, n - 1, j + 1, n - 1, j + 2])
			if mat[n - 1][j + 1] == 1:
				flip(n - 1, j + 1)
				flip(n - 2, j)
				flip(n - 2, j + 1)
				k += 1
				out.append([n, j + 2, n - 1, j + 1, n - 1, j + 2])
			j += 2
	while i < n - 1:
		j = 0
		if m % 2:
			if mat[i][m - 1]:
				flip(i, m - 1)
				flip(i, m - 2)
				flip(i + 1, m - 2)
				k += 1
				out.append([i + 1, m, i + 1, m - 1, i + 2, m - 1])
			if mat[i + 1][m - 1]:
				flip(i + 1, m - 1)
				flip(i, m - 2)
				flip(i + 1, m - 2)
				k += 1
				out.append([i + 2, m, i + 1, m - 1, i + 2, m - 1])
		while j < m - 1:
			func(i, j, i + 1, j + 1)
			j += 2
		i += 2
	print(k)
	for i in out:
		print(*i)


for _ in range(0, int(input())):
	(n, m) = map(int, input().split())
	mat = [[char for char in input()] for _ in range(0, n)]
	answer = []

	def update(changes):
		answer.append((changes[0], changes[1], changes[2]))
		for (x, y) in changes:
			if mat[x][y] == '0':
				mat[x][y] = '1'
			else:
				mat[x][y] = '0'

	def change(a, b, c, vec0, vec1):
		answer.append((a, b, c))
		for (x, y) in [a, b, c]:
			if mat[x][y] == '0':
				vec0.remove((x, y))
				vec1.append((x, y))
				mat[x][y] = '1'
			else:
				vec0.append((x, y))
				vec1.remove((x, y))
				mat[x][y] = '0'
		return (vec0, vec1)
	if n > 2 or m > 2:
		for x in range(0, n, 2):
			for j in range(0, m - 1, 1):
				i = min(n - 2, x)
				if mat[i][j] == '0' and mat[i + 1][j] == '0':
					continue
				changes = []
				if mat[i][j] == '1':
					changes.append((i, j))
				if mat[i + 1][j] == '1':
					changes.append((i + 1, j))
				if len(changes) < 3:
					changes.append((i, j + 1))
				if len(changes) < 3:
					changes.append((i + 1, j + 1))
				update(changes)
		for x in range(0, n - 2):
			i = x
			j = m - 2
			if mat[i][j] == '0' and mat[i][j + 1] == '0':
				continue
			changes = []
			if mat[i][j] == '1':
				changes.append((i, j))
			if mat[i][j + 1] == '1':
				changes.append((i, j + 1))
			if len(changes) < 3:
				changes.append((i + 1, j))
			if len(changes) < 3:
				changes.append((i + 1, j + 1))
			update(changes)
	a = n - 2
	b = m - 2
	vec0 = [(x, y) for x in range(a, a + 2) for y in range(b, b + 2) if mat[x][y] == '0']
	vec1 = [(x, y) for x in range(a, a + 2) for y in range(b, b + 2) if mat[x][y] == '1']
	cnt = 0
	while len(vec1) > 0:
		if len(vec1) == 4:
			(vec0, vec1) = change(vec1[0], vec1[1], vec1[2], vec0, vec1)
		elif len(vec1) == 3:
			(vec0, vec1) = change(vec1[0], vec1[1], vec1[2], vec0, vec1)
		else:
			(vec0, vec1) = change(vec0[0], vec0[1], vec1[0], vec0, vec1)
	print(len(answer))
	for (x, y, z) in answer:
		print(x[0] + 1, x[1] + 1, y[0] + 1, y[1] + 1, z[0] + 1, z[1] + 1)


t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	a = [list(map(int, input())) for i in range(n)]

	def add(p):
		a[p[0]][p[1]] ^= 1
		a[p[2]][p[3]] ^= 1
		a[p[4]][p[5]] ^= 1
		ans.append(' '.join(map(lambda x: str(x + 1), p)))
	ans = []
	for i in range(n - 1, 1, -1):
		for j in range(m):
			if a[i][j]:
				add((i, j, i - 1, j, i - 1, j + (1 if j < m - 1 else -1)))
	for j in range(m - 1, 1, -1):
		for i in (0, 1):
			if a[i][j]:
				add((i, j, 0, j - 1, 1, j - 1))
	for i in (0, 1):
		for j in (0, 1):
			if (a[0][0] + a[0][1] + a[1][0] + a[1][1] + a[i][j]) % 2:
				add((i ^ 1, j, i, j ^ 1, i ^ 1, j ^ 1))
	print(len(ans))
	print('\n'.join(ans))


import sys

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

def mint():
	return int(minp())

def mints():
	return map(int, minp().split())

def solve():
	(n, m) = mints()
	a = [list(map(int, minp())) for i in range(n)]
	ans = []
	for i in range(n - 2):
		l = a[i]
		ll = a[i + 1]
		for j in range(m - 1):
			if l[j] == 1:
				if l[j + 1] == 1:
					ans.append((i, j, i, j + 1, i + 1, j))
					l[j + 1] ^= 1
					ll[j] ^= 1
				else:
					ans.append((i, j, i + 1, j, i + 1, j + 1))
					ll[j] ^= 1
					ll[j + 1] ^= 1
			elif l[j + 1] == 1:
				ans.append((i, j + 1, i + 1, j, i + 1, j + 1))
				l[j + 1] ^= 1
				ll[j] ^= 1
				ll[j + 1] ^= 1
	aa = a[n - 2]
	bb = a[n - 1]
	for j in range(m - 2):
		if aa[j] == 1:
			if bb[j] == 1:
				ans.append((n - 2, j, n - 1, j, n - 2, j + 1))
				aa[j + 1] ^= 1
			else:
				ans.append((n - 2, j, n - 2, j + 1, n - 1, j + 1))
				aa[j + 1] ^= 1
				bb[j + 1] ^= 1
		elif bb[j] == 1:
			ans.append((n - 1, j, n - 2, j + 1, n - 1, j + 1))
			aa[j + 1] ^= 1
			bb[j + 1] ^= 1
	c = [(n - 2, m - 2), (n - 2, m - 1), (n - 1, m - 2), (n - 1, m - 1)]
	while True:
		ss = 0
		for (x, y) in c:
			ss += a[x][y]
		if ss == 0:
			break
		if ss == 1 or ss == 3:
			for i in range(4):
				(x, y) = c[i]
				if a[x][y] == 0:
					break
		if ss == 2:
			for i in range(4):
				(x, y) = c[i]
				if a[x][y] == 1:
					break
		if ss == 4:
			i = 0
		d = c.copy()
		d.pop(i)
		tmp = []
		for (x, y) in d:
			a[x][y] ^= 1
			tmp.append(x)
			tmp.append(y)
		ans.append(tmp)
	print(len(ans))
	for l in ans:
		print(' '.join([str(i + 1) for i in l]))
for i in range(mint()):
	solve()