![]() |
VOOZH | about |
Write a code which inputs two numbers m and n and creates a matrix of size m x n (m rows and n columns) in which every elements is either X or 0. The Xs and 0s must be filled alternatively, the matrix should have outermost rectangle of Xs, then a rectangle of 0s, then a rectangle of Xs, and so on.
Examples:
Input: m = 3, n = 3 Output: Following matrix X X X X 0 X X X X Input: m = 4, n = 5 Output: Following matrix X X X X X X 0 0 0 X X 0 0 0 X X X X X X Input: m = 5, n = 5 Output: Following matrix X X X X X X 0 0 0 X X 0 X 0 X X 0 0 0 X X X X X X Input: m = 6, n = 7 Output: Following matrix X X X X X X X X 0 0 0 0 0 X X 0 X X X 0 X X 0 X X X 0 X X 0 0 0 0 0 X X X X X X X X
We strongly recommend to minimize the browser and try this yourself first.
This question was asked in campus recruitment of Shreepartners Gurgaon. I followed the following approach.
Algorithm:
Following is implementation of the above approach.
Output for m = 5, n = 6 X X X X X X X 0 0 0 0 X X 0 X X 0 X X 0 0 0 0 X X X X X X X Output for m = 4, n = 4 X X X X X 0 0 X X 0 0 X X X X X Output for m = 3, n = 4 X X X X X 0 0 X X X X X
Time Complexity: O(mn)
Auxiliary Space: O(mn)