Problem of the day
You are given two integers N and M. You are required to return the matrix of size N * M characters such that every element of the matrix can be X or O, and it must satisfy the following condition.
The Xs and Os must be filled. Alternatively, the matrix should have the outermost rectangle of Xs, then a rectangle of Os, then a rectangle of Xs, and so on.
For Example:N = 3 and M = 3
Required Matrix-
XXX
XOX
XXX
The first line contains a single integer ‘T’ denoting the number of test cases to be run. Then the test cases follow.
The first line of each test case contains two integers ‘N’ and ‘M’ denoting the number of rows and columns in the required matrix.
Output Format:
For each test case print 'N' strings denoting 2D matrix satisfying the above conditions.
Note
You are not required to print anything; it has already been taken care of. Just implement the function and return the matrix.
1 <= T <= 50
1 <= N <= 100
1 <= M <= 100
Time Limit: 1 sec.
2
4 4
3 4
XXXX
XOOX
XOOX
XXXX
XXXX
XOOX
XXXX
In test case 1:
N is 4 and M is also 4, so a matrix of size 4 * 4 is required to output. In the matrix, the outermost rectangle is filled with X and then adjacent to it with O and so on.
Hence the required matrix will be :
XXXX
XOOX
XOOX
XXXX
In test case 2:
N is 3 and M is also 4, so a matrix of size 3 * 4 is required to output. In the matrix, the outermost rectangle is filled with X and then adjacent to it with O and so on.
Hence the required matrix will be :
XXXX
XOOX
XXXX
2
5 3
1 2
XXX
XOX
XOX
XOX
XXX
XXX
Try to fill each rectangle one by one.
We can see that for, given ‘N’ and ‘M’, we have exactly (min('N', ‘M’) + 1) / 2 rectangles to fill. So, we can iterate through each and every rectangle starting from the outermost one and fill it with the required character.
Algorithm-
O(N * M), where ‘N’ is the number of rows in the matrix and ‘M’ is the number of columns in the matrix.
We are visiting each cell at once so it will take ‘N’ * ‘M’ iterations, hence, time complexity will be O(N * M).
O(N * M), where ‘N’ is the number of rows in the matrix and ‘M’ is the number of columns in the matrix.
We are using a matrix of size ‘N’ * ‘M’ to store the answer so, space complexity will be O(N * M).