Last Updated: 19 Dec, 2020

Create A Matrix With Alternating X And 0

Easy
Asked in companies
AdobeZoho Corporation

Problem statement

You are given two integers ‘N’ and ‘M’. Your task is to create a matrix of size N x M in which every element is either ‘X’ or ‘0’. The ‘X’s and ‘0’s must be filled alternatively, the matrix should have an outermost rectangle of ‘X’s, then a rectangle of ‘0’s, then a rectangle of ‘X’s, and so on.

For example :
For given dimension N = 5 and M = 5 :

[      [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 Format :
The first line of input contains an integer 'T' representing the number of the test case. Then the test case follows.

Each test case contains two integers ‘N’ and ‘M’ which denotes the dimensions of the matrix that you need to create.
Output Format :
For each test case, print the matrix of dimension N x M.
Note :
You do not need to print anything; It has already been taken care of. Just implement the given function.  
Constraints :
1 ≤ T ≤ 50
1 ≤ N ≤ 100
1 ≤ M ≤ 100

Where ‘T’ is the number of test cases.
‘N’ and ‘M’ are the given dimensions.

Time Limit: 1 sec 

Approaches

01 Approach

Our intuition is to create rectangular frames one by one such that the outermost frame consists of ‘X’s and then that of ‘0’s and again ‘X’s and so on. To implement this we need to create alternate frames of ‘X’s and ‘0’s and thereby create the whole matrix of size ‘N’ x ‘M’. 

 

Steps are as follows:

 

  1. Firstly, create a 2D matrix which will be our constructed matrix.
  2. Now fill the characters of the matrix in spiral form, where every iteration fills the matrix with either ‘X’ or ‘0’ values.
  3. Starting from the value ‘X’, we need to fill ‘X’ in the first row, last column, last row, and the first column of the remaining matrix rows and columns which is nothing but the outermost rectangular frame of the remaining frames.
  4. For the next frame flip the value ‘X’ to ‘0’, and do the same for this frame, we need to fill ‘0’ in the first row, last column, last row, and the first column of the remaining matrix rows and columns which is nothing but the outermost rectangular frame of the remaining frames.
  5. Follow steps 3 and 4 alternatively until you are out of frames.