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
- Count number of islands where every island is row-wise and column-wise separated
- Find a common element in all rows of a given row-wise sorted matrix
- Given a matrix of ‘O’ and ‘X’, replace 'O' with 'X' if surrounded by 'X'
- Print all elements in sorted order from row and column wise sorted matrix
- Mobile Numeric Keypad Problem
- Given an n x n square matrix, find sum of all sub-squares of size k x k
- Program to multiply two matrices
- Kth smallest element in a row-wise and column-wise sorted 2D array | Set 1
- Zigzag (or diagonal) traversal of Matrix
- Maximum sum rectangle in a 2D matrix | DP-27
- Inplace (Fixed space) M x N size matrix transpose | Updated
- Print unique rows in a given boolean matrix
- Find the row with maximum number of 1s
- Print a given matrix in spiral form
- Search in a row wise and column wise sorted matrix