


Suppose you are at position (x, y) then you can move to : [ (x + 1 , y ), ( x - 1 , y ), ( x , y + 1), (x , y - 1), (x + 1, y + 1), (x + 1, y - 1), (x - 1, y + 1), (x - 1, y - 1) ].
If ‘N’ = 2, ‘M’ = 2, 'STR’ = "a" and the input matrix is
[ [ ab ]
[ ed ] ]
We need to find the maximum length of the path from starting character ’a’. So the maximum length is 2, which is [a, b]. Hence, the answer is [2].
The first line contains a single integer 'T' representing the number of test cases.
The first line of each test case contains two integers, ‘N’ and ‘M’, denoting the number of rows and columns of the character array ‘matrix’.
The next ‘N’ lines of each test case contain a string consisting of ‘M’ characters denoting the elements of the array 'matrix'.
The last line of each test case contains the string ‘STR‘, which contains starting characters(without space).
For each test case, print the space-separated array of integers where each integer is the length of the longest path from the character at that index in the string ‘STR’.
Print the output of each test case in a separate line.
You do not need to print anything. It has already been taken care of. Just implement the given function.
1 <= T <= 10
1 <= M <= 300
1 <= N <= 300
‘a’ <= matrix[i][j], STR[i] <= ‘z’
1 <= |STR[i]| <= 26
Time Limit: 1 sec
In this approach, we are going to implement a recursive function. We will traverse the array matrix for each character of STR as a starting character. We will check if matrix[i][j] is equal to STR[index] then, we will create a function call to find the longest path.
As we have discussed in the previous approach, we will create a recursive function to find the longest path. This approach will maintain a dynamic array dpMatrix that stores the maximum length using the character present at that index in the matrix as starting character. This helps to remove the repetitive tasks and reduces the time complexity.