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.
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.
1) Use the code for Printing Matrix in Spiral form.
2) Instead of printing the array, inserted the element ‘X’ or ‘0’ alternatively in the array.
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)
Please suggest if someone has a better solution which is more efficient in terms of space and time.
This article is contributed by Deepak Bisht. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
- Number of rectangles in N*M grid
- Find if two rectangles overlap
- Find all rectangles filled with 0
- Sum of Areas of Rectangles possible for an array
- Smallest square formed with given rectangles
- Number of rectangles in a circle of radius R
- Maximum given sized rectangles that can be cut out of a sheet of paper
- Intersecting rectangle when bottom-left and top-right corners of two rectangles are given
- Number of unique rectangles formed using N unit squares
- Count the number of rectangles such that ratio of sides lies in the range [a,b]
- Find the number of rectangles of size 2*1 which can be placed inside a rectangle of size n*m
- Check if matrix can be converted to another matrix by transposing square sub-matrices
- Largest subset of rectangles such that no rectangle fit in any other rectangle
- Program to check diagonal matrix and scalar matrix
- Circular Matrix (Construct a matrix with numbers 1 to m*n in spiral way)