Given an M × N binary matrix, fill it with alternating rectangles of 1’s and 0’s.

For example,

Input: 10 × 8 matrix
 
Output:
 
  1   1   1   1   1   1   1   1
  1   0   0   0   0   0   0   1
  1   0   1   1   1   1   0   1
  1   0   1   0   0   1   0   1
  1   0   1   0   0   1   0   1
  1   0   1   0   0   1   0   1
  1   0   1   0   0   1   0   1
  1   0   1   1   1   1   0   1
  1   0   0   0   0   0   0   1
  1   1   1   1   1   1   1   1

Practice this problem

The idea is to fill the matrix by following the spiral order. All elements involved in each alternating run in spiral order are filled by either 0 or 1 based on input from the last run. Four loops are used to maintain the spiral order, each for the top, right, bottom, and left corner of the matrix.

Following is the implementation in C++, Java, and Python based on the above idea:

C++


Download  Run Code

Java


Download  Run Code

Python


Download  Run Code

Output:
 
  1   1   1   1   1   1   1   1
  1   0   0   0   0   0   0   1
  1   0   1   1   1   1   0   1
  1   0   1   0   0   1   0   1
  1   0   1   0   0   1   0   1
  1   0   1   0   0   1   0   1
  1   0   1   0   0   1   0   1
  1   0   1   1   1   1   0   1
  1   0   0   0   0   0   0   1
  1   1   1   1   1   1   1   1

Another Approach

An M × N matrix has min(ceil(M/2), ceil(N/2)) rectangular cycles. A cycle is formed by i'th row, (N-i+1)'th column, (M-i+1)'th row, and i'th column where i varies from 1 to min(ceil(M/2), ceil(N/2)). The idea is for each rectangular cycle, associate a value to it. For the outer cycle, the value will be 0; for the second cycle, the value will be 1, and the third cycle will have a value of 2, and so on… The following figure shows 4 cycles in a 10 × 8 matrix marked by the value 0–3:

 0   0   0   0   0   0   0   0
 0   1   1   1   1   1   1   0
 0   1   2   2   2   2   1   0
 0   1   2   3   3   2   1   0
 0   1   2   3   3   2   1   0
 0   1   2   3   3   2   1   0
 0   1   2   3   3   2   1   0
 0   1   2   2   2   2   1   0
 0   1   1   1   1   1   1   0
 0   0   0   0   0   0   0   0

Depending upon whether the assigned value is odd or even for a matrix cell, assign 0 or 1 to the output matrix. The algorithm can be implemented as follows in C++, Java, and Python:

C++


Download  Run Code

Java


Download  Run Code

Python


Download  Run Code

Output:
 
  1   1   1   1   1   1   1   1
  1   0   0   0   0   0   0   1
  1   0   1   1   1   1   0   1
  1   0   1   0   0   1   0   1
  1   0   1   0   0   1   0   1
  1   0   1   0   0   1   0   1
  1   0   1   0   0   1   0   1
  1   0   1   1   1   1   0   1
  1   0   0   0   0   0   0   1
  1   1   1   1   1   1   1   1

The time complexity of the proposed solution is O(M × N) for an M × N matrix and doesn’t require any extra space.