Given a matrix of size ‘N’ x ’M’. Each cell in a grid has a character denoting the next cell that can be visited from the current cell. If 'MATRIX'[i][j] is equal to:
‘U’:- then from (i,j) you can visit (i - 1, j) only if i - 1 >= 0.
‘D’:- then from (i,j) you can visit (i + 1, j) only if i + 1 < n.
‘R’:- then from (i,j) you can visit (i, j + 1) only if j + 1 < m.
‘L’:- then from (i,j) you can visit (i, j - 1) only if j - 1 >= 0.
You can change the direction of each cell at most one time.
You need to determine a minimum number of changes you need to make to reach from the cell (0,0) to the cell('N' - 1, 'M' - 1).
The first line contains a single integer ‘T’ denoting the number of test cases.
The first line of the test case contains 2 integers ‘N’ and ‘M’ denoting the length and width of the matrix.
The next ‘N’ lines contain ‘M’ characters each denoting the direction of the cell of the matrix.
Output Format:
For each test case, print a single integer denoting a minimum number of cell’s direction need to change to reach from (0,0) to ('N' - 1, 'M' - 1).
Print the output of each test case in a separate line.
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 <=100
MATRIX[i][j] = {‘D’,’R’,’U’,’L’}.
Time limit: 1 sec
2
3 3
DDD
RRL
UUU
2 2
UU
DD
1
2
In test case 1, one of the paths is as follows:
(0,0) --> (1,0) --> (1,1) --> (1,2). Change the direction of (1,2) from ‘L’ to ‘D’. (1,2) -> (2,2).
In test case 2, one of the paths is as follows:
Change the direction of (0,0) cell to ‘R’.
(0,0) --> (0,1).
Change the direction of (0,1) cell from ‘U’ to ‘D’.
(0,1) --> (1,1).
Thus 2 changes are needed to reach (1,1) cell.
2
1 1
D
2 2
RD
RD
0
0
In test case 1, there is only one cell and so, we don't need any cell to change its direction. Thus, 0 will be the output.
In test case 2, No changes are required. Thus, 0 will be the output.
Use BFS to find a minimum number of changes to reach from. (0,0) cell to all other cells and it will lead us to get minimum answer.
Explanation:-The main idea is to use a breadth-first search to find minimum changes to reach from the cell (0,0) to all other cells. The cell will be added in the queue if the steps of the current cell is less than the given cell.
The steps are as follows:
O(N * M), Where ‘N’ and ‘M’ are number of rows and columns.
Since we will traverse all cells. Total number of cells are N * M. Hence time complexity is O(N * M).
O(N * M), Where ‘N’ and ‘M’ are number of rows and columns.
Since we are creating an auxiliary matrix of size N * M. Hence space complexity is O(N * M).