
1) A fixed obstacle denoted by ‘ * ’
2) A stone denotes by ‘ # ’
3) Empty space denoted by ‘ . ’
You may consider the stones to be heavy and rotational force has no effect on them. That is: the stones do not re-align themselves during the rotation.
If N = 1 and M = 6 and box is:
‘#’ , ‘.’ , ‘.’ , ‘*’ , ‘#’ , ‘.’
The box after rotation becomes:
‘.’
‘.’
‘#’
‘*’
‘.’
‘#’
The first line contains a single integer ‘T’ denoting the number of test cases, then each test case follows:
The first line of each test case contains two integers ‘N’ and ‘M’ denoting the dimensions of the box initially.
The next ‘N’ lines each contain ‘M’ characters denoting the cell of the box.
For each test case, print the box after re-aligning, the new box is of dimensions M*N.
Output for each test case will be printed in a separate line.
You are not required to print anything; it has already been taken care of. Just implement the function.
1 ≤ T ≤ 10
1 ≤ N, M ≤ 250
Box[i][j] = { ‘ * ’ , ‘ # ‘ , ‘ . ‘ }
Time limit: 1 sec
We can simply shift all the stones first, and then rotate the matrix, this will be our final result and we won’t have to re-align the stones after the rotation!
Why? Try to imagine what happens after rotation!
The rotation simply pushes all the boxes to extreme right positions. We can simply take that effect into account first on the N*M matrix and after that simply rotate the box without making re-alignments and returning an M*N matrix.
To shift the elements to the extreme right. Use a pointer to keep the track of the rightmost available cell for a stone. To implement it, simply consider each row at a time, and initialize a pointer to point to the last column initially. Now while iterating the row from right to left, if you encounter a stone ‘#’, then simply swap it with the cell pointer by pointer and decrement the value of the pointer, and in case you encounter an obstacle ‘*’ then change the value of the pointer to point to the left cell of the obstacle.
In the end, simply rotate the box and return it.
The steps are as follows :