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
GeeksforGeeks has prepared a complete interview preparation course with premium videos, theory, practice problems, TA support and many more features. Please refer Placement 100 for details
- Sum of Areas of Rectangles possible for an array
- Find if two rectangles overlap
- Find all rectangles filled with 0
- Number of rectangles in N*M grid
- 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
- Minimum steps required to convert the matrix into lower hessenberg matrix
- Minimum number of steps to convert a given matrix into Diagonally Dominant Matrix
- Minimum number of steps to convert a given matrix into Upper Hessenberg matrix
- Largest subset of rectangles such that no rectangle fit in any other rectangle