Create an n x n square matrix, where all the sub-matrix have the sum of opposite corner elements as even
Given an integer N. The task is to generate a square matrix of ( n x n ) having the elements ranging from 1 to n^2 with the following condition:
- The elements of the matrix should be distinct i.e used only once
- Numbers ranging from 1 to n^2
- Every sub-matrix you choose should have the sum of opposite corner elements as even i.e sum of top left and bottom right should be even and the sum of top right and bottom left element should be even
This property should apply to all the submatrices of the matrix. You need to generate an Even Sub-Matrix
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course
Output: 1 2
Explanation: Here sum of 1+3=4 is even and 2+4=6 is even
Output: 1 2 3
4 5 6
7 8 9
Explanation: The sub matrix [1 2 4 5], [2 3 5 6], [4 5 7 8], [5 6 8 9], [1 2 3 4 5 6 7 8 9] satisfies the condition of opposite corner
elements having even sum
As we know for any two elements sum to be even it can be Sum of ODD and ODD or Sum of EVEN and EVEN. In either of the two cases for the corner elements sum to be even we need to ensure that the diagonal pattern arranged elements should be either odd or even. So we make the 2d array having diagonals as all odds or all evens to find any submatrix having corner elements sum even. The below approach can be followed for the same.
- When n is odd the diagonals are already in all odd or even elements, so we need not modify and generate a simple 2d array
- When n is even the matrix generated does not satisfy the property having an even sum of opposite corner elements of the sub-matrices, so we reverse the alternate row elements so that diagonals of every submatrix are either all odd or all even.
Below is the implementation.
1 2 3 4 8 7 6 5 9 10 11 12 16 15 14 13
This approach takes O(n*2) time complexity.