You are given a matrix of size $n \times n$ filled with lowercase English letters. You can change no more than $k$ letters in this matrix.

Consider all paths from the upper left corner to the lower right corner that move from a cell to its neighboring cell to the right or down. Each path is associated with the string that is formed by all the letters in the cells the path visits. Thus, the length of each string is $2n - 1$.

Find the lexicographically smallest string that can be associated with a path after changing letters in at most $k$ cells of the matrix.

A string $a$ is lexicographically smaller than a string $b$, if the first different letter in $a$ and $b$ is smaller in $a$.


-----Input-----

The first line contains two integers $n$ and $k$ ($1 \le n \le 2000$, $0 \le k \le n^2$) — the size of the matrix and the number of letters you can change.

Each of the next $n$ lines contains a string of $n$ lowercase English letters denoting one row of the matrix.


-----Output-----

Output the lexicographically smallest string that can be associated with some valid path after changing no more than $k$ letters in the matrix.


-----Examples-----
Input
4 2
abcd
bcde
bcad
bcde

Output
aaabcde

Input
5 3
bwwwz
hrhdh
sepsp
sqfaf
ajbvw

Output
aaaepfafw

Input
7 6
ypnxnnp
pnxonpm
nxanpou
xnnpmud
nhtdudu
npmuduh
pmutsnz

Output
aaaaaaadudsnz



-----Note-----

In the first sample test case it is possible to change letters 'b' in cells $(2, 1)$ and $(3, 1)$ to 'a', then the minimum path contains cells $(1, 1), (2, 1), (3, 1), (4, 1), (4, 2), (4, 3), (4, 4)$. The first coordinate corresponds to the row and the second coordinate corresponds to the column.

Difficulty: HARD
Tags: Greedy algorithms
Skill types: Greedy algorithms

Starter code:

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

class FastIO(IOBase):
	newlines = 0

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

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

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

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

class IOWrapper(IOBase):

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

def bootstrap(f, stack=[]):

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

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

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

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

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

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

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

def main():
	(n, k) = RL()
	arr = [input() for _ in range(n)]
	dp = [[INF] * n for _ in range(n)]
	q = deque()
	pre = 0
	for i in range(n):
		for j in range(n):
			if i == 0 and j == 0:
				dp[0][0] = 1 if arr[0][0] != 'a' else 0
			elif i == 0:
				dp[0][j] = dp[0][j - 1] + (1 if arr[0][j] != 'a' else 0)
			elif j == 0:
				dp[i][0] = dp[i - 1][0] + (1 if arr[i][0] != 'a' else 0)
			else:
				dp[i][j] = min(dp[i - 1][j], dp[i][j - 1]) + (1 if arr[i][j] != 'a' else 0)
			if dp[i][j] <= k:
				pre = max(pre, i + j + 1)
	suf = 2 * n - 1 - pre
	res = ['a'] * pre + ['z'] * suf
	vis = [[0] * n for _ in range(n)]
	q = []
	for i in range(n):
		for j in range(n):
			if dp[i][j] == k and i + j + 1 == pre:
				if i + 1 < n and vis[i + 1][j] == 0:
					q.append((i + 1, j))
					vis[i + 1][j] = 1
				if j + 1 < n and vis[i][j + 1] == 0:
					q.append((i, j + 1))
					vis[i][j + 1] = 1
	q.sort(key=lambda a: arr[a[0]][a[1]])
	if not q:
		q.append((0, 0))
	for i in range(pre, len(res)):
		newq = []
		res[i] = arr[q[0][0]][q[0][1]]
		for j in range(len(q)):
			now = arr[q[j][0]][q[j][1]]
			if now != res[i]:
				break
			for (nx, ny) in [[1, 0], [0, 1]]:
				(xx, yy) = (nx + q[j][0], ny + q[j][1])
				if xx < n and yy < n and (vis[xx][yy] == 0):
					vis[xx][yy] = 1
					if newq:
						if arr[xx][yy] > arr[newq[-1][0]][newq[-1][1]]:
							continue
						elif arr[xx][yy] < arr[newq[-1][0]][newq[-1][1]]:
							newq = []
					newq.append((xx, yy))
		q = newq
	print(''.join(res))
main()


from array import array
inf = 1 << 30

def main():
	(n, k) = [int(x) for x in input().split(' ')]
	Matrix = []
	for i in range(n):
		Matrix.append(array('b', [ord(x) for x in input()]))
	dp = [array('l', [inf for j in range(n)]) for i in range(n)]
	direct = [[ord('d') for j in range(n)] for i in range(n)]
	opt = ''
	for s in range(2 * n - 1):
		opchar = chr(ord('z') + 1)
		positions = []
		for i in range(0, s + 1):
			j = s - i
			if j < n and i < n:
				if i > 0 and j > 0:
					if dp[i - 1][j] < dp[i][j - 1]:
						dp[i][j] = dp[i - 1][j]
						direct[i][j] = 'l'
					else:
						dp[i][j] = dp[i][j - 1]
						direct[i][j] = 'd'
				elif i > 0:
					dp[i][j] = dp[i - 1][j]
					direct[i][j] = 'l'
				elif j > 0:
					dp[i][j] = dp[i][j - 1]
					direct[i][j] = 'd'
				else:
					dp[i][j] = 0
					direct[i][j] = 'e'
				if dp[i][j] < k and Matrix[i][j] is not ord('a'):
					dp[i][j] += 1
					Matrix[i][j] = ord('a')
				if Matrix[i][j] < ord(opchar) and dp[i][j] <= k:
					opchar = chr(Matrix[i][j])
		for i in range(0, s + 1):
			j = s - i
			if j < n and i < n:
				if Matrix[i][j] is not ord(opchar):
					dp[i][j] = inf
	ans = ''
	(a, b) = (n - 1, n - 1)
	while direct[a][b] is not 'e':
		ans += chr(Matrix[a][b])
		if direct[a][b] is 'l':
			a -= 1
		else:
			b -= 1
	ans += chr(Matrix[0][0])
	print(ans[::-1])
main()


def solve(m, matrix, good, n):
	c = 'z'
	for x in range(n):
		y = m - x
		if y < 0 or y >= n:
			continue
		if not good[x][y]:
			continue
		if x < n - 1:
			c = min(c, matrix[x + 1][y])
		if y < n - 1:
			c = min(c, matrix[x][y + 1])
	for x in range(n):
		y = m - x
		if y < 0 or y >= n:
			continue
		if not good[x][y]:
			continue
		if x < n - 1 and matrix[x + 1][y] == c:
			good[x + 1][y] = 1
		if y < n - 1 and matrix[x][y + 1] == c:
			good[x][y + 1] = 1
	return c

def main():
	(n, k) = map(int, input().split())
	matrix = []
	for i in range(n):
		s = list(input())
		matrix.append(s)
	dp = [[0 for i in range(n)] for j in range(n)]
	good = [[0 for i in range(n)] for j in range(n)]
	dp[0][0] = 0 if matrix[0][0] == 'a' else 1
	for i in range(1, n):
		dp[0][i] = dp[0][i - 1]
		if matrix[0][i] != 'a':
			dp[0][i] += 1
		dp[i][0] = dp[i - 1][0]
		if matrix[i][0] != 'a':
			dp[i][0] += 1
	for i in range(1, n):
		for j in range(1, n):
			dp[i][j] = min(dp[i - 1][j], dp[i][j - 1])
			if matrix[i][j] != 'a':
				dp[i][j] += 1
	m = -1
	for i in range(n):
		for j in range(n):
			if dp[i][j] <= k:
				m = max(m, i + j)
	if m == -1:
		print(matrix[0][0], end='')
		m = 0
		good[0][0] = 1
	else:
		for i in range(m + 1):
			print('a', end='')
		for i in range(n):
			y = m - i
			if y < 0 or y >= n:
				continue
			if dp[i][y] <= k:
				good[i][y] = 1
	while m < 2 * n - 2:
		res = solve(m, matrix, good, n)
		print(res, end='')
		m += 1
main()


def main():
	(n, k) = readIntArr()
	arr = []
	for _ in range(n):
		arr.append(input())
	maxAinPath = [[0 for _ in range(n)] for __ in range(n)]
	for i in range(n):
		for j in range(n):
			if i > 0:
				maxAinPath[i][j] = max(maxAinPath[i][j], maxAinPath[i - 1][j])
			if j > 0:
				maxAinPath[i][j] = max(maxAinPath[i][j], maxAinPath[i][j - 1])
			if arr[i][j] == 'a':
				maxAinPath[i][j] += 1
	if maxAinPath[n - 1][n - 1] + k >= 2 * n - 1:
		print('a' * (2 * n - 1))
	else:
		potential = []
		for i in range(n):
			for j in range(n):
				if 1 + i + j == maxAinPath[i][j] + k:
					potential.append([i, j])
		maxLen = -inf
		for (i, j) in potential:
			maxLen = max(maxLen, i + j)
		if maxLen == -inf:
			ans = []
		else:
			ans = ['a'] * (maxLen + 1)
		bfs = []
		for (i, j) in potential:
			if i + j == maxLen:
				bfs.append((i, j))
		if len(bfs) == 0:
			bfs.append((0, 0))
			ans.append(arr[0][0])
		while len(ans) < 2 * n - 1:
			bfs2 = set()
			for (i, j) in bfs:
				if i + 1 < n:
					bfs2.add((i + 1, j))
				if j + 1 < n:
					bfs2.add((i, j + 1))
			minLetter = 'z'
			for (i, j) in bfs2:
				letter = arr[i][j]
				minLetter = min(minLetter, letter)
			ans.append(minLetter)
			bfs = []
			for (i, j) in bfs2:
				if arr[i][j] == minLetter:
					bfs.append((i, j))
			assert len(bfs) > 0
		print(''.join(ans))
	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()]
inf = float('inf')
MOD = 10 ** 9 + 7
main()