VOOZH about

URL: https://www.geeksforgeeks.org/dsa/create-a-matrix-with-alternating-rectangles-of-0-and-x/

⇱ Create a matrix with alternating rectangles of O and X - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Create a matrix with alternating rectangles of O and X

Last Updated : 23 Jul, 2025

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.

  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.

Algorithm:

  1. Start with initializing variables i, k, and l to 0 and x to 'X'.
  2. Create a 2D character array a with m rows and n columns.
  3. Store the values of m and n in variables r and c respectively for later use.
  4. Use a while loop to fill the array a with alternating rectangles of '0' and 'X' characters in a spiral pattern.
  5. In the while loop, fill the first row of the remaining rows with 'X' character, starting from column l to n-1, and then increment k by 1.
  6. Fill the last column of the remaining columns with 'X' character, starting from row k to m-1, and then decrement n by 1.
  7. Fill the last row of the remaining rows with 'X' character, starting from column n-1 to l, and then decrement m by 1.
  8. Fill the first column of the remaining columns with 'X' character, starting from row m-1 to k, and then increment l by 1.
  9. After each iteration of the while loop, toggle the character x between '0' and 'X'.
  10. After the while loop is completed, print the filled matrix a row by row.

Following is implementation of the above approach.  


Output
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)

Comment
Article Tags: