After a hard-working week Polycarp prefers to have fun. Polycarp's favorite entertainment is drawing snakes. He takes a rectangular checkered sheet of paper of size $n \times m$ (where $n$ is the number of rows, $m$ is the number of columns) and starts to draw snakes in cells.

Polycarp draws snakes with lowercase Latin letters. He always draws the first snake with the symbol 'a', the second snake with the symbol 'b', the third snake with the symbol 'c' and so on. All snakes have their own unique symbol. There are only $26$ letters in the Latin alphabet, Polycarp is very tired and he doesn't want to invent new symbols, so the total number of drawn snakes doesn't exceed $26$.

Since by the end of the week Polycarp is very tired, he draws snakes as straight lines without bends. So each snake is positioned either vertically or horizontally. Width of any snake equals $1$, i.e. each snake has size either $1 \times l$ or $l \times 1$, where $l$ is snake's length. Note that snakes can't bend.

When Polycarp draws a new snake, he can use already occupied cells for drawing the snake. In this situation, he draws the snake "over the top" and overwrites the previous value in the cell.

Recently when Polycarp was at work he found a checkered sheet of paper with Latin letters. He wants to know if it is possible to get this sheet of paper from an empty sheet by drawing some snakes according to the rules described above. If it is possible, he is interested in a way to draw snakes.


-----Input-----

The first line of the input contains one integer $t$ ($1 \le t \le 10^5$) — the number of test cases to solve. Then $t$ test cases follow.

The first line of the test case description contains two integers $n$, $m$ ($1 \le n,m \le 2000$) — length and width of the checkered sheet of paper respectively.

Next $n$ lines of test case description contain $m$ symbols, which are responsible for the content of the corresponding cell on the sheet. It can be either lowercase Latin letter or symbol dot ('.'), which stands for an empty cell.

It is guaranteed that the total area of all sheets in one test doesn't exceed $4\cdot10^6$.


-----Output-----

Print the answer for each test case in the input.

In the first line of the output for a test case print YES if it is possible to draw snakes, so that you can get a sheet of paper from the input. If it is impossible, print NO.

If the answer to this question is positive, then print the way to draw snakes in the following format. In the next line print one integer $k$ ($0 \le k \le 26$) — number of snakes. Then print $k$ lines, in each line print four integers $r_{1,i}$, $c_{1,i}$, $r_{2,i}$ and $c_{2,i}$ — coordinates of extreme cells for the $i$-th snake ($1 \le r_{1,i}, r_{2,i} \le n$, $1 \le c_{1,i}, c_{2,i} \le m$). Snakes should be printed in order of their drawing. If there are multiple solutions, you are allowed to print any of them.

Note that Polycarp starts drawing of snakes with an empty sheet of paper.


-----Examples-----
Input
1
5 6
...a..
..bbb.
...a..
.cccc.
...a..

Output
YES
3
1 4 5 4
2 3 2 5
4 2 4 5

Input
3
3 3
...
...
...
4 4
..c.
adda
bbcb
....
3 5
..b..
aaaaa
..b..

Output
YES
0
YES
4
2 1 2 4
3 1 3 4
1 3 3 3
2 2 2 3
NO

Input
2
3 3
...
.a.
...
2 2
bb
cc

Output
YES
1
2 2 2 2
YES
3
1 1 1 2
1 1 1 2
2 1 2 2

Source: codeforces | Difficulty: HARD
Tags: Implementation

Complete search


Solutions:
import os, io
inp = io.BytesIO(os.read(0, os.fstat(0).st_size))
input = lambda : inp.readline().rstrip().decode('ascii')
from collections import defaultdict as di

def solve():
	(n, m) = map(int, input().split())
	B = [input() for _ in range(n)]
	pos = di(list)
	for i in range(n):
		b = B[i]
		for j in range(m):
			pos[b[j]].append((i, j))
	if '.' in pos:
		del pos['.']
	C = [list('.' * m) for _ in range(n)]
	moves = []
	if pos:
		mxx = max(pos)
		for i in range(97, ord(mxx) + 1):
			c = chr(i)
			if c not in pos:
				pos[c] = pos[mxx]
			P = pos[c]
			if all((p[0] == P[0][0] for p in P)):
				mn = min((p[1] for p in P))
				mx = max((p[1] for p in P))
				i = P[0][0]
				for j in range(mn, mx + 1):
					C[i][j] = c
				moves.append((i + 1, mn + 1, i + 1, mx + 1))
			elif all((p[1] == P[0][1] for p in P)):
				mn = min((p[0] for p in P))
				mx = max((p[0] for p in P))
				j = P[0][1]
				for i in range(mn, mx + 1):
					C[i][j] = c
				moves.append((mn + 1, j + 1, mx + 1, j + 1))
	if [''.join(s) for s in C] == B:
		print('YES')
		print(len(moves))
		for m in moves:
			print(*m)
	else:
		print('NO')

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


def naiveSolve():
	return
from collections import defaultdict

def main():
	t = int(input())
	allans = []
	for _ in range(t):
		(n, m) = readIntArr()
		grid = []
		for __ in range(n):
			grid.append(input())
		ok = True
		snakes = defaultdict(lambda : [])
		for i in range(n):
			for j in range(m):
				if grid[i][j] != '.':
					snakes[grid[i][j]].append([i, j])
					l = len(snakes[grid[i][j]])
					if l > max(n, m):
						ok = False
						break
			if ok == False:
				break
		if ok == False:
			allans.append(['NO'])
			continue
		startEnd = dict()
		for (letter, coords) in snakes.items():
			if len(coords) >= 2:
				if coords[0][0] == coords[1][0]:
					for i in range(2, len(coords)):
						if coords[0][0] != coords[i][0]:
							ok = False
							break
				elif coords[0][1] == coords[1][1]:
					for i in range(2, len(coords)):
						if coords[0][1] != coords[i][1]:
							ok = False
							break
				else:
					ok = False
			if ok == False:
				break
			startEnd[letter] = [coords[0], coords[-1]]
		if ok == False:
			allans.append(['NO'])
			continue
		adj = defaultdict(lambda : [])
		for (letter, [start, end]) in startEnd.items():
			if start[0] == end[0]:
				for col in range(start[1], end[1] + 1):
					letter2 = grid[start[0]][col]
					if letter != letter2:
						if letter2 == '.':
							ok = False
						else:
							adj[letter].append(letter2)
			else:
				for row in range(start[0], end[0] + 1):
					letter2 = grid[row][start[1]]
					if letter != letter2:
						if letter2 == '.':
							ok = False
						else:
							adj[letter].append(letter2)
		if ok == False:
			allans.append(['NO'])
			continue
		chars = startEnd.keys()
		for u in chars:
			for v in adj[u]:
				if v < u:
					ok = False
		if ok == False:
			allans.append(['NO'])
			continue
		order = sorted(chars)
		allans.append(['YES'])
		if len(order) == 0:
			allans.append([0])
		else:
			allC = 'abcdefghijklmnopqrstuvwxyz'
			maxChar = order[-1]
			maxCharIdx = allC.index(maxChar)
			allans.append([maxCharIdx + 1])
			(dr, dc) = startEnd[order[-1]][0]
			dr += 1
			dc += 1
			for i in range(maxCharIdx + 1):
				if allC[i] not in order:
					allans.append([dr, dc, dr, dc])
				else:
					([r1, c1], [r2, c2]) = startEnd[allC[i]]
					r1 += 1
					c1 += 1
					r2 += 1
					c2 += 1
					allans.append([r1, c1, r2, c2])
	multiLineArrayOfArraysPrint(allans)
	return
import sys
input = lambda : sys.stdin.readline().rstrip('\r\n')

def oneLineArrayPrint(arr):
	print(' '.join([str(x) for x in arr]))

def multiLineArrayPrint(arr):
	print('\n'.join([str(x) for x in arr]))

def multiLineArrayOfArraysPrint(arr):
	print('\n'.join([' '.join([str(x) for x in y]) for y in arr]))

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

def makeArr(defaultValFactory, dimensionArr):
	dv = defaultValFactory
	da = dimensionArr
	if len(da) == 1:
		return [dv() for _ in range(da[0])]
	else:
		return [makeArr(dv, da[1:]) for _ in range(da[0])]

def queryInteractive(l, r):
	print('? {} {}'.format(l, r))
	sys.stdout.flush()
	return int(input())

def answerInteractive(x):
	print('! {}'.format(x))
	sys.stdout.flush()
inf = float('inf')
MOD = 998244353
from math import gcd, floor, ceil
for _abc in range(1):
	main()


import sys
input = sys.stdin.readline

def solve():
	(H, W) = map(int, input().split())
	G = [[ord(s) - 46 for s in input().strip()] for _ in range(H)]
	Gy = list(map(list, zip(*G)))
	k = 0
	St = [None] * 77
	for (h, G1) in enumerate(G, 1):
		k = max(k, max(G1))
		for (w, g) in enumerate(G1, 1):
			if not g:
				continue
			if St[g] is None:
				St[g] = (h, w)
			elif type(St[g]) == tuple:
				(h1, w1) = St[g]
				if h == h1:
					St[g] = h
				elif w == w1:
					St[g] = -w
				else:
					return False
			else:
				if St[g] == h or St[g] == -w:
					continue
				return False
	if k == 0:
		return []
	A = []
	for j in range(k, 50, -1):
		if St[j] is None:
			A.append(A[-1])
			continue
		if type(St[j]) == tuple:
			A.append(St[j] * 2)
			continue
		x = St[j]
		if x > 0:
			Gh = G[x - 1]
			p = None
			e = None
			for (ig, g) in enumerate(Gh):
				if g == j:
					p = ig
					break
			for (ig, g) in enumerate(Gh[::-1]):
				ig = W - 1 - ig
				if g == j:
					e = ig
					break
			for ig in range(p, e + 1):
				if Gh[ig] < j:
					return False
			A.append((x, p + 1, x, e + 1))
		else:
			Gw = Gy[-x - 1]
			p = None
			e = None
			for (ig, g) in enumerate(Gw):
				if g == j:
					p = ig
					break
			for (ig, g) in enumerate(Gw[::-1]):
				ig = H - 1 - ig
				if g == j:
					e = ig
					break
			for ig in range(p, e + 1):
				if Gw[ig] < j:
					return False
			A.append((p + 1, -x, e + 1, -x))
	return A[::-1]
T = int(input())
for _ in range(T):
	ans = solve()
	if ans is False:
		print('NO')
		continue
	print('YES')
	print(len(ans))
	for a in ans:
		print(*a)


from collections import defaultdict as di

def solve():
	(n, m) = map(int, input().split())
	B = [input() for _ in range(n)]
	pos = di(list)
	for i in range(n):
		b = B[i]
		for j in range(m):
			pos[b[j]].append((i, j))
	if '.' in pos:
		del pos['.']
	C = [list('.' * m) for _ in range(n)]
	moves = []
	if pos:
		mxx = max(pos)
		for i in range(97, ord(mxx) + 1):
			c = chr(i)
			if c not in pos:
				pos[c] = pos[mxx]
			P = pos[c]
			if all((p[0] == P[0][0] for p in P)):
				mn = min((p[1] for p in P))
				mx = max((p[1] for p in P))
				i = P[0][0]
				for j in range(mn, mx + 1):
					C[i][j] = c
				moves.append((i + 1, mn + 1, i + 1, mx + 1))
			elif all((p[1] == P[0][1] for p in P)):
				mn = min((p[0] for p in P))
				mx = max((p[0] for p in P))
				j = P[0][1]
				for i in range(mn, mx + 1):
					C[i][j] = c
				moves.append((mn + 1, j + 1, mx + 1, j + 1))
	if [''.join(s) for s in C] == B:
		print('YES')
		print(len(moves))
		for m in moves:
			print(*m)
	else:
		print('NO')

def main():
	t = int(input())
	for _ in range(t):
		solve()
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')
import sys

class ostream:

	def __lshift__(self, a):
		sys.stdout.write(str(a))
		return self
cout = ostream()
endl = '\n'

def readnumbers(zero=0):
	conv = ord if py2 else lambda x: x
	A = []
	numb = zero
	sign = 1
	i = 0
	s = sys.stdin.buffer.read()
	try:
		while True:
			if s[i] >= b'0'[0]:
				numb = 10 * numb + conv(s[i]) - 48
			elif s[i] == b'-'[0]:
				sign = -1
			elif s[i] != b'\r'[0]:
				A.append(sign * numb)
				numb = zero
				sign = 1
			i += 1
	except:
		pass
	if s and s[-1] >= b'0'[0]:
		A.append(sign * numb)
	return A
main()


import sys

def solve():
	(H, W) = map(int, sys.stdin.readline().split())
	G = [[ord(s) - 46 for s in sys.stdin.readline().strip()] for _ in range(H)]
	k = 0
	inf = 10 ** 9
	Stbw = [-inf] * 77
	Stsw = [inf] * 77
	Stbh = [-inf] * 77
	Stsh = [inf] * 77
	for (h, G1) in enumerate(G, 1):
		k = max(k, max(G1))
		for (w, g) in enumerate(G1, 1):
			if not g:
				continue
			Stbw[g] = max(Stbw[g], w)
			Stsw[g] = min(Stsw[g], w)
			Stbh[g] = max(Stbh[g], h)
			Stsh[g] = min(Stsh[g], h)
	if k == 0:
		return []
	A = []
	for j in range(k, 50, -1):
		if Stbw[j] == -inf and Stbh[j] == -inf:
			A.append(A[-1])
			continue
		bw = Stbw[j] == Stsw[j]
		bh = Stbh[j] == Stsh[j]
		if not bw and (not bh):
			return False
		if bw:
			w = Stbw[j] - 1
			for h in range(Stsh[j] - 1, Stbh[j]):
				if G[h][w] < j:
					return False
		elif bh:
			h = Stbh[j] - 1
			for w in range(Stsw[j] - 1, Stbw[j]):
				if G[h][w] < j:
					return False
		A.append((Stsh[j], Stsw[j], Stbh[j], Stbw[j]))
	return A[::-1]
T = int(input())
for _ in range(T):
	ans = solve()
	if ans is False:
		print('NO')
		continue
	print('YES')
	print(len(ans))
	for a in ans:
		print(*a)


import sys
input = sys.stdin.readline
testcases = int(input())
for testcase in range(testcases):
	(n, m) = list(map(int, input().split()))
	MAP = [input().strip() for i in range(n)]
	STR = [[] for i in range(26)]
	for i in range(n):
		for j in range(m):
			if MAP[i][j] != '.':
				STR[ord(MAP[i][j]) - 97].append([i, j])
	for s in range(25, -1, -1):
		if STR[s] == []:
			continue
		(x, y) = STR[s][0]
		(z, w) = STR[s][-1]
		flag = 1
		if x == z:
			for k in range(y, w + 1):
				if MAP[x][k] >= chr(s + 97):
					continue
				else:
					flag = 0
					break
			for (u, v) in STR[s]:
				if u == x:
					continue
				else:
					flag = 0
					break
		elif y == w:
			for k in range(x, z + 1):
				if MAP[k][y] >= chr(s + 97):
					continue
				else:
					flag = 0
					break
			for (u, v) in STR[s]:
				if v == y:
					continue
				else:
					flag = 0
					break
		else:
			flag = 0
		if flag == 0:
			print('NO')
			break
	else:
		print('YES')
		for s in range(25, -1, -1):
			if STR[s] != []:
				ANS = s + 1
				ANONE = STR[s][0]
				print(ANS)
				break
		else:
			print(0)
			continue
		for ans in range(ANS):
			if STR[ans] != []:
				print(STR[ans][0][0] + 1, STR[ans][0][1] + 1, STR[ans][-1][0] + 1, STR[ans][-1][1] + 1)
			else:
				print(ANONE[0] + 1, ANONE[1] + 1, ANONE[0] + 1, ANONE[1] + 1)


import sys
inp = iter(sys.stdin.buffer.read().splitlines())
input = lambda : next(inp).decode('ascii')
from collections import defaultdict as di

def solve():
	(n, m) = map(int, input().split())
	B = [input() for _ in range(n)]
	pos = di(list)
	for i in range(n):
		b = B[i]
		for j in range(m):
			pos[b[j]].append((i, j))
	if '.' in pos:
		del pos['.']
	C = [list('.' * m) for _ in range(n)]
	moves = []
	if pos:
		mxx = max(pos)
		for i in range(97, ord(mxx) + 1):
			c = chr(i)
			if c not in pos:
				pos[c] = pos[mxx]
			P = pos[c]
			if all((p[0] == P[0][0] for p in P)):
				mn = min((p[1] for p in P))
				mx = max((p[1] for p in P))
				i = P[0][0]
				for j in range(mn, mx + 1):
					C[i][j] = c
				moves.append((i + 1, mn + 1, i + 1, mx + 1))
			elif all((p[1] == P[0][1] for p in P)):
				mn = min((p[0] for p in P))
				mx = max((p[0] for p in P))
				j = P[0][1]
				for i in range(mn, mx + 1):
					C[i][j] = c
				moves.append((mn + 1, j + 1, mx + 1, j + 1))
	if [''.join(s) for s in C] == B:
		print('YES')
		print(len(moves))
		for m in moves:
			print(*m)
	else:
		print('NO')

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


import sys
t = int(input())
for ti in range(t):
	(n, m) = list(map(int, input().split()))
	a = []
	for i in range(n):
		a.append(input())
	top = {}
	bot = {}
	l = {}
	r = {}
	res = True
	for y in range(n):
		for x in range(m):
			c = a[y][x]
			if c != '.':
				if c not in top:
					top[c] = y
					bot[c] = y
					l[c] = x
					r[c] = x
				elif top[c] == y:
					r[c] = x
					xi = x - 1
					while xi >= 0 and a[y][xi] != c:
						if a[y][xi] == '.' or a[y][xi] < c:
							res = False
						xi -= 1
				elif l[c] == x and r[c] == x:
					bot[c] = y
					yi = y - 1
					while yi >= 0 and a[yi][x] != c:
						if a[yi][x] == '.' or a[yi][x] < c:
							res = False
						yi -= 1
				else:
					res = False
	if len(top) == 0:
		sys.stdout.write('YES\n')
		sys.stdout.write('0\n')
	elif res:
		mxc = max(top)
		cnt = ord(mxc) & 31
		sys.stdout.write('YES\n')
		sys.stdout.write(str(cnt) + '\n')
		for i in range(cnt):
			ci = chr(ord('a') + i)
			if ci not in top:
				ci = mxc
			sys.stdout.write(f'{top[ci] + 1} {l[ci] + 1} {bot[ci] + 1} {r[ci] + 1}\n')
	else:
		sys.stdout.write('NO\n')


def naiveSolve():
	return
from collections import defaultdict

def charToInt(c):
	if c == '.':
		return -1
	return ord(c) - ord('a')

def main():
	t = int(input())
	allans = []
	for _ in range(t):
		(n, m) = readIntArr()
		grid = []
		for __ in range(n):
			row = list(input())
			grid.append([charToInt(c) for c in row])
		start = [None] * 26
		end = [None] * 26
		for i in range(n):
			for j in range(m):
				if grid[i][j] != -1:
					if start[grid[i][j]] == None:
						start[grid[i][j]] = [i, j]
					end[grid[i][j]] = [i, j]
		while start and start[-1] == None:
			start.pop()
			end.pop()
		if len(start) == 0:
			allans.append(['YES'])
			allans.append([0])
			continue
		ok = True
		N = len(start)
		(dr, dc) = end[N - 1]
		ans = [[dr, dc, dr, dc] for __ in range(N)]
		for i in range(N):
			if start[i] == None:
				continue
			if start[i][0] != end[i][0] and start[i][1] != end[i][1]:
				ok = False
				break
			ans[i] = [*start[i], *end[i]]
		if ok == False:
			allans.append(['NO'])
			continue
		reconstruct = [[-1 for _z in range(m)] for __ in range(n)]
		for i in range(N):
			(r1, c1, r2, c2) = ans[i]
			if r1 == r2:
				for col in range(c1, c2 + 1):
					reconstruct[r1][col] = i
			else:
				assert c1 == c2
				for row in range(r1, r2 + 1):
					reconstruct[row][c1] = i
		for i in range(n):
			for j in range(m):
				if grid[i][j] != reconstruct[i][j]:
					ok = False
		if ok == False:
			allans.append(['NO'])
			continue
		allans.append(['YES'])
		allans.append([N])
		for a in ans:
			for j in range(4):
				a[j] += 1
		allans.extend(ans)
	multiLineArrayOfArraysPrint(allans)
	return
import sys
input = lambda : sys.stdin.readline().rstrip('\r\n')

def oneLineArrayPrint(arr):
	print(' '.join([str(x) for x in arr]))

def multiLineArrayPrint(arr):
	print('\n'.join([str(x) for x in arr]))

def multiLineArrayOfArraysPrint(arr):
	print('\n'.join([' '.join([str(x) for x in y]) for y in arr]))

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

def makeArr(defaultValFactory, dimensionArr):
	dv = defaultValFactory
	da = dimensionArr
	if len(da) == 1:
		return [dv() for _ in range(da[0])]
	else:
		return [makeArr(dv, da[1:]) for _ in range(da[0])]

def queryInteractive(l, r):
	print('? {} {}'.format(l, r))
	sys.stdout.flush()
	return int(input())

def answerInteractive(x):
	print('! {}'.format(x))
	sys.stdout.flush()
inf = float('inf')
MOD = 998244353
from math import gcd, floor, ceil
for _abc in range(1):
	main()


import sys
input = sys.stdin.readline
T = int(input())
for _ in range(T):
	(N, M) = map(int, input().split())
	mar = [-1] * 26
	mir = [2000] * 26
	mac = [-1] * 26
	mic = [2000] * 26
	X = [[-1 if a == '.' else ord(a) - 97 for a in input()] for i in range(N)]
	R = [[a + 1 for a in range(M)] for _ in range(N)]
	D = [[i + 1] * M for i in range(N)]
	ma = -1
	for i in range(N):
		for j in range(M):
			k = X[i][j]
			if k >= 0:
				mar[k] = max(mar[k], i)
				mir[k] = min(mir[k], i)
				mac[k] = max(mac[k], j)
				mic[k] = min(mic[k], j)
				ma = max(ma, k)
	f = 0
	ans = 1
	ANS = []
	for k in range(ma + 1)[::-1]:
		if f and mar[k] == -1 and (mir[k] == 2000):
			ANS.append(ANS[-1])
		elif mar[k] == mir[k]:
			r = mar[k]
			c = mic[k]
			while c <= mac[k]:
				if X[r][c] < k:
					ans = 0
					break
				c = R[r][c]
			else:
				ANS.append((r + 1, mic[k] + 1, r + 1, mac[k] + 1))
			R[r][mic[k]] = mac[k] + 1
			if ans == 0:
				break
			f = 1
		elif mac[k] == mic[k]:
			c = mac[k]
			r = mir[k]
			while r <= mar[k]:
				if X[r][c] < k:
					ans = 0
					break
				r = D[r][c]
			else:
				ANS.append((mir[k] + 1, c + 1, mar[k] + 1, c + 1))
			D[mir[k]][c] = mar[k] + 1
			if ans == 0:
				break
			f = 1
		else:
			ans = 0
			break
	if ans == 0:
		print('NO')
	else:
		print('YES')
		print(len(ANS))
		for a in ANS[::-1]:
			print(*a)


import sys
input = iter(sys.stdin.read().splitlines()).__next__
from collections import defaultdict as dd, deque
import io
bio = io.BytesIO()

def solve():
	(n, m) = map(int, input().split())
	B = [input() for _ in range(n)]
	pos = dd(list)
	for i in range(n):
		b = B[i]
		for j in range(m):
			pos[b[j]].append((i, j))
	if '.' in pos:
		del pos['.']
	C = [list('.' * m) for _ in range(n)]
	moves = []
	if pos:
		mxx = max(pos)
		for i in range(97, ord(mxx) + 1):
			c = chr(i)
			if c not in pos:
				pos[c] = pos[mxx]
			P = pos[c]
			if all((p[0] == P[0][0] for p in P)):
				mn = min((p[1] for p in P))
				mx = max((p[1] for p in P))
				i = P[0][0]
				for j in range(mn, mx + 1):
					C[i][j] = c
				moves.append((i, mn, i, mx))
			elif all((p[1] == P[0][1] for p in P)):
				mn = min((p[0] for p in P))
				mx = max((p[0] for p in P))
				j = P[0][1]
				for i in range(mn, mx + 1):
					C[i][j] = c
				moves.append((mn, j, mx, j))
	if [''.join(s) for s in C] == B:
		bio.write(b'YES\n')
		bio.write(str(len(moves)).encode() + b'\n')
		for m in moves:
			bio.write(' '.join((str(x + 1) for x in m)).encode() + b'\n')
	else:
		bio.write(b'NO\n')
t = int(input())
for _ in range(t):
	solve()
sys.stdout.buffer.write(bio.getvalue())


from collections import defaultdict as di
import sys, os, atexit
from io import BytesIO
inp = BytesIO(sys.stdin.buffer.read())
input = lambda : inp.readline().decode('ascii')
buf = BytesIO()
sys.stdout.write = lambda s: buf.write(s.encode('ascii'))
atexit.register(lambda : sys.__stdout__.buffer.write(buf.getvalue()))

def solve():
	(n, m) = map(int, input().split())
	B = [input().rstrip() for _ in range(n)]
	pos = di(list)
	for i in range(n):
		b = B[i]
		for j in range(m):
			pos[b[j]].append((i, j))
	if '.' in pos:
		del pos['.']
	C = [list('.' * m) for _ in range(n)]
	moves = []
	if pos:
		mxx = max(pos)
		for i in range(97, ord(mxx) + 1):
			c = chr(i)
			if c not in pos:
				pos[c] = pos[mxx]
			P = pos[c]
			if all((p[0] == P[0][0] for p in P)):
				mn = min((p[1] for p in P))
				mx = max((p[1] for p in P))
				i = P[0][0]
				for j in range(mn, mx + 1):
					C[i][j] = c
				moves.append((i + 1, mn + 1, i + 1, mx + 1))
			elif all((p[1] == P[0][1] for p in P)):
				mn = min((p[0] for p in P))
				mx = max((p[0] for p in P))
				j = P[0][1]
				for i in range(mn, mx + 1):
					C[i][j] = c
				moves.append((mn + 1, j + 1, mx + 1, j + 1))
	if [''.join(s) for s in C] == B:
		print('YES')
		print(len(moves))
		for m in moves:
			print(*m)
	else:
		print('NO')
t = int(input())
for _ in range(t):
	solve()


from sys import stdin, stdout
from collections import defaultdict

def process():
	let_to_squares = defaultdict(list)
	square_to_lets = defaultdict(list)
	(n, m) = map(int, stdin.readline().split())
	grid = []
	for i in range(n):
		row = stdin.readline().strip()
		grid.append([c for c in row])
	max_let = 0
	for i in range(n):
		for j in range(m):
			let = grid[i][j]
			if let == '.':
				continue
			max_let = max(ord(let), max_let)
			let_to_squares[let].append((i, j))
	if max_let == 0:
		stdout.write('YES\n0\n')
		return
	for i in range(n):
		for j in range(m):
			if ord(grid[i][j]) == max_let:
				any_square = [i + 1, j + 1, i + 1, j + 1]
	remaining = defaultdict(int)
	coords = {}
	for let in let_to_squares.keys():
		row_min = n + 1
		col_min = m + 1
		row_max = -1
		col_max = -1
		for (i, j) in let_to_squares[let]:
			row_min = min(row_min, i)
			row_max = max(row_max, i)
			col_min = min(col_min, j)
			col_max = max(col_max, j)
		coords[let] = [row_min + 1, col_min + 1, row_max + 1, col_max + 1]
		if row_min != row_max and col_min != col_max:
			stdout.write('NO\n')
			return
		for i in range(row_min, row_max + 1):
			for j in range(col_min, col_max + 1):
				if grid[i][j] != let:
					if grid[i][j] == '.':
						stdout.write('NO\n')
						return
					remaining[let] += 1
					square_to_lets[i, j].append(let)
	for let in range(max_let, ord('a') - 1, -1):
		if remaining[chr(let)] != 0:
			stdout.write('NO\n')
			return
		for (i, j) in let_to_squares[chr(let)]:
			for new_let in square_to_lets[i, j]:
				remaining[new_let] -= 1
	stdout.write('YES\n')
	stdout.write(str(max_let - ord('a') + 1) + '\n')
	for let in range(ord('a'), max_let + 1):
		if chr(let) in coords:
			t = coords[chr(let)]
		else:
			t = any_square
		stdout.write(' '.join(map(str, t)) + '\n')
t = int(stdin.readline())
for it in range(t):
	process()


import sys
input = sys.stdin.readline
T = int(input())
for _ in range(T):
	(n, m) = map(int, input().split())
	minx = {}
	maxx = {}
	miny = {}
	maxy = {}
	matrix = []
	for i in range(n):
		matrix.append(list(input().strip()))
	for i in range(n):
		for j in range(m):
			if matrix[i][j] != '.':
				try:
					minx[matrix[i][j]] = min(minx[matrix[i][j]], j)
				except:
					minx[matrix[i][j]] = j
				try:
					maxx[matrix[i][j]] = max(maxx[matrix[i][j]], j)
				except:
					maxx[matrix[i][j]] = j
				try:
					miny[matrix[i][j]] = min(miny[matrix[i][j]], i)
				except:
					miny[matrix[i][j]] = i
				try:
					maxy[matrix[i][j]] = max(maxy[matrix[i][j]], i)
				except:
					maxy[matrix[i][j]] = i
	copy = []
	for i in range(n):
		copy.append([])
		for j in range(m):
			copy[-1].append('.')
	for char in range(ord('a'), ord('z') + 1):
		char = chr(char)
		try:
			if minx[char] == maxx[char]:
				c = minx[char]
				for r in range(miny[char], maxy[char] + 1):
					copy[r][c] = char
			else:
				r = miny[char]
				for c in range(minx[char], maxx[char] + 1):
					copy[r][c] = char
		except:
			pass
	if matrix == copy:
		print('YES')
		cnt = -1
		for char in range(ord('z'), ord('a') - 1, -1):
			char = chr(char)
			try:
				minx[char] += 0
				break
			except:
				pass
		else:
			cnt = 0
		if cnt != 0:
			cnt = ord(char) - ord('a') + 1
		print(cnt)
		ans = []
		for char in range(ord('a'), ord('a') + cnt):
			char = chr(char)
			try:
				ans.append((miny[char], minx[char], maxy[char], maxx[char]))
			except:
				pass
		i = 0
		for char in range(ord('a'), ord('a') + cnt):
			char = chr(char)
			print(ans[i][0] + 1, ans[i][1] + 1, ans[i][2] + 1, ans[i][3] + 1)
			try:
				minx[char] += 0
				i += 1
			except:
				pass
	else:
		print('NO')


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
mod = 10 ** 9 + 7
mod1 = 998244353
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

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

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

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

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

class IOWrapper(IOBase):

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

class TreeNode:

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

class AvlTree:

	def __init__(self):
		self._tree = None

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

class SegmentTree1:

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

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

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

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

	def __len__(self):
		return self._len

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

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

class SegmentTree:

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

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

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

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

	def __len__(self):
		return self._len

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

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

class Factorial:

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

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

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

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

class Combination:

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

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

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

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

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

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

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

def 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

class TrieNode:

	def __init__(self):
		self.children = [None] * 26
		self.isEndOfWord = False

class Trie:

	def __init__(self):
		self.root = self.getNode()

	def getNode(self):
		return TrieNode()

	def _charToIndex(self, ch):
		return ord(ch) - ord('a')

	def insert(self, key):
		pCrawl = self.root
		length = len(key)
		for level in range(length):
			index = self._charToIndex(key[level])
			if not pCrawl.children[index]:
				pCrawl.children[index] = self.getNode()
			pCrawl = pCrawl.children[index]
		pCrawl.isEndOfWord = True

	def search(self, key):
		pCrawl = self.root
		length = len(key)
		for level in range(length):
			index = self._charToIndex(key[level])
			if not pCrawl.children[index]:
				return False
			pCrawl = pCrawl.children[index]
		return pCrawl != None and pCrawl.isEndOfWord

class Node:

	def __init__(self, data):
		self.data = data
		self.count = 0
		self.left = None
		self.right = None

class BinaryTrie:

	def __init__(self):
		self.root = Node(0)

	def insert(self, pre_xor):
		self.temp = self.root
		for i in range(31, -1, -1):
			val = pre_xor & 1 << i
			if val:
				if not self.temp.right:
					self.temp.right = Node(0)
				self.temp = self.temp.right
				self.temp.count += 1
			if not val:
				if not self.temp.left:
					self.temp.left = Node(0)
				self.temp = self.temp.left
				self.temp.count += 1
		self.temp.data = pre_xor

	def query(self, xor):
		self.temp = self.root
		for i in range(31, -1, -1):
			val = xor & 1 << i
			if not val:
				if self.temp.left and self.temp.left.count > 0:
					self.temp = self.temp.left
				elif self.temp.right:
					self.temp = self.temp.right
			elif self.temp.right and self.temp.right.count > 0:
				self.temp = self.temp.right
			elif self.temp.left:
				self.temp = self.temp.left
			self.temp.count -= 1
		return xor ^ self.temp.data
t = int(input())
for ik in range(t):
	(n, m) = map(int, input().split())
	l = []
	f = 0
	d = defaultdict(list)
	for i in range(n):
		l.append(input())
	for i in range(n):
		for j in range(m):
			d[l[i][j]].append((i, j))
	for i in d:
		d[i].sort()
	ans = [['.' for i in range(m)] for j in range(n)]
	w = []
	c = 0
	for i in range(97, 123):
		if len(d[chr(i)]) == 0:
			c += 1
			continue
		else:
			a = d[chr(i)][0]
			b = d[chr(i)][-1]
			for j in range(c + 1):
				w.append((a, b))
			c = 0
			if a[0] == b[0]:
				for j in range(a[1], b[1] + 1):
					ans[a[0]][j] = chr(i)
			else:
				for j in range(a[0], b[0] + 1):
					ans[j][a[1]] = chr(i)
	for i in range(n):
		for j in range(m):
			if ans[i][j] == l[i][j]:
				continue
			else:
				f = 1
				print('NO')
				break
		if f == 1:
			break
	if f == 0:
		print('YES')
		print(len(w))
		for i in range(len(w)):
			print(w[i][0][0] + 1, w[i][0][1] + 1, w[i][1][0] + 1, w[i][1][1] + 1)


import os, sys
from io import BytesIO, IOBase

def solve(arr, apl, n, m, aaju_baju):
	ans = 0
	ans1 = []
	arr1 = [['.'] * m for _ in range(n)]
	for i in range(26):
		if apl[i] == [-1, -1]:
			if aaju_baju[i] != [-1, -1]:
				ans += 1
				ans1.append(aaju_baju[i] + aaju_baju[i])
			continue
		ans1.append([apl[i][0], apl[i][1], apl[i][0], apl[i][1]])
		ans += 1
		(fl, fl1) = (0, 0)
		z = chr(i + 97)
		arr1[apl[i][0]][apl[i][1]] = z
		for j in range(apl[i][0] + 1, n):
			if arr[j][apl[i][1]] == z:
				fl = 1
				(ans1[-1][2], ans1[-1][3]) = (j, apl[i][1])
		for j in range(apl[i][1] + 1, m):
			if arr[apl[i][0]][j] == z:
				fl1 = 1
				(ans1[-1][2], ans1[-1][3]) = (apl[i][0], j)
		if fl:
			for xx in range(ans1[-1][0], ans1[-1][2] + 1):
				arr1[xx][ans1[-1][1]] = z
		if fl1:
			for xx in range(ans1[-1][1], ans1[-1][3] + 1):
				arr1[ans1[-1][0]][xx] = z
		if fl and fl1:
			return 'NO'
	return ('YES', ans, ans1, arr1)

def main():
	for _ in range(int(input())):
		(n, m) = map(int, input().split())
		arr = [input().strip() for _ in range(n)]
		apl = [[-1, -1] for _ in range(26)]
		for i in range(n - 1, -1, -1):
			for j in range(m - 1, -1, -1):
				if arr[i][j] != '.':
					apl[ord(arr[i][j]) - 97] = [i, j]
		aaju_baju = [[-1, -1] for _ in range(26)]
		xx = [-1, -1]
		for i in range(25, -1, -1):
			if apl[i] != [-1, -1]:
				xx = apl[i]
			aaju_baju[i] = xx
		zz = solve(arr, apl, n, m, aaju_baju)
		if zz == 'NO':
			print(zz)
		else:
			for i in range(n):
				zz[3][i] = ''.join(zz[3][i])
			if arr != zz[3]:
				print('NO')
			else:
				print(zz[0])
				print(zz[1])
				for i in zz[2]:
					for j in i:
						print(j + 1, end=' ')
					print()
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 os
import sys
import math
from io import BytesIO, IOBase
from fractions import Fraction
import collections
from itertools import permutations
from collections import defaultdict
from collections import deque
import threading
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

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

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

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

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

class IOWrapper(IOBase):

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

class SegmentTree:

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

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

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

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

	def __len__(self):
		return self._len

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

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

class SegmentTree1:

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

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

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

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

	def __len__(self):
		return self._len

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

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

class Factorial:

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

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

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

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

class Combination:

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

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

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

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

def binarySearch1(arr, n, key):
	left = 0
	right = n - 1
	mid = 0
	res = arr[0]
	while left <= right:
		mid = (right + left) // 2
		if arr[mid] > key:
			right = mid - 1
		else:
			res = arr[mid]
			left = mid + 1
	return res
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	a = []
	for i in range(n):
		a.append(list(input()))
	d = defaultdict(list)
	check = [[0 for j in range(m)] for i in range(n)]
	fake = [0, 0, 0, 0]
	mx = 96
	for ch in range(122, 96, -1):
		c = 0
		for i in range(n):
			for j in range(m):
				if a[i][j] == chr(ch):
					s = [i + 1, j + 1, i + 1, j + 1]
					mx = max(mx, ch)
					if fake[0] == 0:
						fake = s.copy()
					check[i][j] = 1
					x = 0
					if i < n - 1 and ord(a[i + 1][j]) >= ch:
						k = i
						while k < n - 1 and ord(a[k + 1][j]) >= ch:
							if ord(a[k + 1][j]) > ch and check[k + 1][j] == 0:
								break
							if ord(a[k + 1][j]) == ch:
								x = 1
							k += 1
						if x:
							k = i
							while k < n - 1 and ord(a[k + 1][j]) >= ch:
								if ord(a[k + 1][j]) > ch and check[k + 1][j] == 0:
									break
								k += 1
								check[k][j] = 1
								s[2] = k + 1
								s[3] = j + 1
					if x == 0 and j < m - 1 and (ord(a[i][j + 1]) >= ch):
						k = j
						while k < m - 1 and ord(a[i][k + 1]) >= ch:
							if ord(a[i][k + 1]) > ch and check[i][k + 1] == 0:
								break
							k += 1
							check[i][k] = 1
							s[2] = i + 1
							s[3] = k + 1
					c = 1
					d[ch] = s
					break
			if c:
				break
	res = []
	c = 1
	for i in range(n):
		for j in range(m):
			if a[i][j] != '.' and check[i][j] == 0:
				c = 0
				break
		if c == 0:
			break
	for i in range(97, mx + 1):
		if len(d[i]) == 0:
			res.append(fake)
		elif len(d[i]) == 4:
			res.append(d[i])
	if c:
		print('YES')
		print(len(res))
		for i in res:
			print(*i)
	else:
		print('NO')


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

def S_():
	return input()

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

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

def MI():
	return map(int, 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 StoI():
	return [ord(i) - 97 for i in input()]

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

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

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

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

def show(*inp, end='\n'):
	if show_flg:
		print(*inp, end=end)
YN = ['Yes', 'No']
mo = 10 ** 9 + 7
inf = float('inf')
l_alp = string.ascii_lowercase
u_alp = string.ascii_uppercase
ts = time.time()
sys.setrecursionlimit(10 ** 5)
input = lambda : sys.stdin.readline().rstrip()

def ran_input():
	import random
	n = random.randint(4, 16)
	(rmin, rmax) = (1, 10)
	a = [random.randint(rmin, rmax) for _ in range(n)]
	return (n, a)
show_flg = False
show_flg = True
ans = 0
t = I()
for _ in range(t):
	(h, w) = LI()
	ans = []
	t = []
	ng = False
	rs = [[inf, -inf] for i in range(26)]
	cs = [[inf, -inf] for i in range(26)]
	for i in range(h):
		s = input()
		t.append(s)
		for j in range(w):
			if s[j] != '.':
				k = ord(s[j]) - 97
				rs[k][0] = min(rs[k][0], i + 1)
				rs[k][1] = max(rs[k][1], i + 1)
				cs[k][0] = min(cs[k][0], j + 1)
				cs[k][1] = max(cs[k][1], j + 1)
	ll = -1
	for i in range(26):
		if rs[i][0] != inf:
			ll = i
	if ll == -1:
		print('YES')
		print(0)
		continue
	for i in range(ll + 1)[::-1]:
		if (rs[i][0] != inf and rs[i][0] != rs[i][1]) and (cs[i][0] != inf and cs[i][0] != cs[i][1]):
			ng = True
			break
		elif rs[i][0] == inf:
			ans.append(lsn)
		else:
			lsn = [rs[i][0], cs[i][0], rs[i][1], cs[i][1]]
			ans.append(lsn)
			for r in range(rs[i][0], rs[i][1] + 1):
				for c in range(cs[i][0], cs[i][1] + 1):
					if ord(t[r - 1][c - 1]) - 97 < i:
						ng = True
	if ng:
		print('NO')
		continue
	else:
		print('YES')
		print(len(ans))
		for i in ans[::-1]:
			print(*i)