So your task is to find the ninja’s minimum distance to the target cell you were being provided with the starting point of the ninja.
Note:1. There is exactly one -1 and 2 in the grid. Remember that you will not have this information in your code.
The first line of input contains an integer ‘T’ which denotes the number of test cases. Then, the ‘T’ test cases follow.
Each test case’s first line contains two space-separated integers, ‘n’ and ‘m’, denoting the number of rows and columns in the ‘grid’.
The next ‘n’ lines contain ‘m’ characters denoting the elements of the matrix.
grid[i][j] == -1 indicates that the ninja is in cell (i, j).
grid[i][j] == 0 indicates that the cell (i, j) is blocked.
grid[i][j] == 1 indicates that the cell (i, j) is empty.
grid[i][j] == 2 indicates that the cell (i, j) is the target cell.
Output format:
For every test case, print the length of the shortest path to the ninja target. If no such path is available, print -1.
Note:
You do not need to print anything, it has already been taken care of. Just implement the given function.
1 <= T <= 10
1 <= N, M <= 10^2
Value in each element of ‘grid’ = {‘-1’, ‘1’, ‘0’, ‘2’}
Where ‘T’ is the number of test cases, ‘N’ is the number of rows, and ‘M’ is the number of columns in a ‘grid’.
Time Limit: 1 sec
1
3 3
0 -1 1
0 0 1
0 1 2
3
Test Case 1:

As you can see in the input matrix first ninja has to move right then down and then again down for reaching the destination. So the minimum steps needed are is ‘3’.
1
3 4
0 -1 1 0
0 0 1 1
0 1 0 2
4
Test Case 1:

As you can see in the input matrix first ninja has to move right then down and then right and then down for reaching the destination. So the minimum steps needed are is ‘4’.
Try to iterate through all the nodes.
Approach: The idea here is to think of a matrix-like graph and do the dfs traversal and by traversing each possible path compare the value to look for the minimum value.
Algorithm:
O(N * M), where ‘N’ is the number of rows and ‘M’is the number of columns
As in the worst case, we have to travel our whole grid, and also in finding the starting position of ninja takes O(N * M) time.
O(N * M), where ‘N’ is the number of rows and ‘M’ is the number of columns.
As we are using a visited array and recursion stack.