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


Input: 2
Output: 1 2
4 3
Explanation: Here sum of 1+3=4 is even and 2+4=6 is even

Input: 4
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 even sum of opposite corner elements of the sub-matrices, so we reverse the alternate row elements so that diagonals of every submatrix is either all odd or all even.

Below is the implementation.






# Even sub-matrix
import itertools
def sub_mat_even(n):
    temp = itertools.count(1)
    # create a 2d array ranging 
    # from 1 to n^2
    l = [[next(temp)for i in range(n)]for i in range(n)]
    # If found even we reverse the alternate 
    # row elements to get all diagnol elements 
    # as all even or all odd
    if n%2 == 0:
        for i in range(0,len(l)):
            if i%2 == 1:
                l[i][:] = l[i][::-1]
    # Printing the array formed
    for i in range(n):
        for j in range(n):
            print(l[i][j],end=" ")
n = 4



1 2 3 4
8 7 6 5
9 10 11 12
16 15 14 13 

My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using or mail your article to See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

Article Tags :

Be the First to upvote.

Please write to us at to report any issue with the above content.