Open In App

Create an n x n square matrix, where all the sub-matrix have the sum of opposite corner elements as even

Last Updated : 04 Aug, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

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

Examples:

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

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

Approach:

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.

C++




// C++ program for
// the above approach
#include <bits/stdc++.h>
using namespace std;
 
void sub_mat_even(int N)
{
  // Counter to initialize
  // the values in 2-D array
  int K = 1;
   
  // To create a 2-D array
  // from to 1 to N*2
  int A[N][N];
   
  for(int i = 0; i < N; i++)
  {
    for(int j = 0; j < N; j++)
    {
      A[i][j] = K;
      K++;
    }
  }
 
  // If found even we reverse
  // the alternate row elements
  // to get all diagonal elements
  // as all even or all odd
  if(N % 2 == 0)
  {
    for(int i = 0; i < N; i++)
    {
      if(i % 2 == 1)
      {
        int s = 0;
        int l = N - 1;
         
        // Reverse the row
        while(s < l)
        {
          swap(A[i][s],
               A[i][l]);
          s++;
          l--;
        }
      }
    }
  }
 
  // Print the formed array
  for(int i = 0; i < N; i++)
  {
    for(int j = 0; j < N; j++)
    {
      cout << A[i][j] << " ";
    }
    cout << endl;
  }
}
 
// Driver code
int main()
{
    int N = 4;
   
    // Function call
    sub_mat_even(N);
}
 
// This code is contributed by mishrapriyanshu557


Java




// Java program for
// the above approach
import java.io.*;
 
class GFG{
 
static void sub_mat_even(int N)
{
     
    // Counter to initialize
    // the values in 2-D array
    int K = 1;
 
    // To create a 2-D array
    // from to 1 to N*2
    int[][] A = new int[N][N];
 
    for(int i = 0; i < N; i++)
    {
        for(int j = 0; j < N; j++)
        {
            A[i][j] = K;
            K++;
        }
    }
 
    // If found even we reverse
    // the alternate row elements
    // to get all diagonal elements
    // as all even or all odd
    if (N % 2 == 0)
    {
        for(int i = 0; i < N; i++)
        {
            if (i % 2 == 1)
            {
                int s = 0;
                int l = N - 1;
 
                // Reverse the row
                while (s < l)
                {
                    swap(A[i], s, l);
                    s++;
                    l--;
                }
            }
        }
    }
 
    // Print the formed array
    for(int i = 0; i < N; i++)
    {
        for(int j = 0; j < N; j++)
        {
            System.out.print(A[i][j] + " ");
        }
        System.out.println();
    }
}
 
private static void swap(int[] A, int s, int l)
{
    int temp = A[s];
    A[s] = A[l];
    A[l] = temp;
}
 
// Driver code
public static void main(String[] args)
{
    int N = 4;
 
    // Function call
    sub_mat_even(N);
}
}
 
// This code is contributed by jithin


Python3




# Python3 program for
# the above approach
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 diagonal 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=" ")
        print()
 
n = 4
sub_mat_even(n)


C#




// C# program for
// the above approach
using System;
class GFG {
     
    static void sub_mat_even(int N)
    {
          
        // Counter to initialize
        // the values in 2-D array
        int K = 1;
      
        // To create a 2-D array
        // from to 1 to N*2
        int[,] A = new int[N, N];
      
        for(int i = 0; i < N; i++)
        {
            for(int j = 0; j < N; j++)
            {
                A[i, j] = K;
                K++;
            }
        }
      
        // If found even we reverse
        // the alternate row elements
        // to get all diagonal elements
        // as all even or all odd
        if (N % 2 == 0)
        {
            for(int i = 0; i < N; i++)
            {
                if (i % 2 == 1)
                {
                    int s = 0;
                    int l = N - 1;
      
                    // Reverse the row
                    while (s < l)
                    {
                        int temp = A[i, s];
                        A[i, s] = A[i, l];
                        A[i, l] = temp;
                        s++;
                        l--;
                    }
                }
            }
        }
      
        // Print the formed array
        for(int i = 0; i < N; i++)
        {
            for(int j = 0; j < N; j++)
            {
                Console.Write(A[i, j] + " ");
            }
            Console.WriteLine();
        }
    }
 
  static void Main() {
       
    int N = 4;
  
    // Function call
    sub_mat_even(N);
  }
}
 
// This code is contributed by divyeshrabadiya07


Output:

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

This approach takes O(n*2) time complexity.



Previous Article
Next Article

Similar Reads

Python | Corner detection with Harris Corner Detection method using OpenCV
Harris Corner detection algorithm was developed to identify the internal corners of an image. The corners of an image are basically identified as the regions in which there are variations in large intensity of the gradient in all possible dimensions and directions. Corners extracted can be a part of the image features, which can be matched with fea
2 min read
Python | Corner Detection with Shi-Tomasi Corner Detection Method using OpenCV
What is a Corner? A corner can be interpreted as the junction of two edges (where an edge is a sudden change in image brightness). Shi-Tomasi Corner Detection - Shi-Tomasi Corner Detection was published by J.Shi and C.Tomasi in their paper 'Good Features to Track'. Here the basic intuition is that corners can be detected by looking for significant
3 min read
Python Program for Convert characters of a string to opposite case
Given a string, convert the characters of the string into the opposite case,i.e. if a character is the lower case then convert it into upper case and vice-versa. Examples: Input : geeksForgEeks Output : GEEKSfORGeEKS Input: hello every one Output: HELLO EVERY ONE Recommended: Please try your approach on {IDE} first, before moving on to the solution
7 min read
Python Program to create a sub-dictionary containing all keys from dictionary list
Given the dictionary list, our task is to create a new dictionary list that contains all the keys, if not, then assign None to the key and persist of each dictionary. Example: Input : test_list = [{'gfg' : 3, 'is' : 7}, {'gfg' : 3, 'is' : 1, 'best' : 5}, {'gfg' : 8}]Output : [{'is': 7, 'best': None, 'gfg': 3}, {'is': 1, 'best': 5, 'gfg': 3}, {'is':
8 min read
Merge the elements in subarray of all even elements of the Array
Given an array arr[] containing N numbers, the task is to merge the subarray of consecutive even numbers by replacing all consecutive even numbers by the first even element of that subarray.Note: A series of even integers are said to be consecutive if there are at least three even numbers in the given series. Therefore, merge elements in subarray w
9 min read
Python program to find tuples which have all elements divisible by K from a list of tuples
Given a list of tuples. The task is to extract all tuples which have all elements divisible by K. Input : test_list = [(6, 24, 12), (60, 12, 6), (12, 18, 21)], K = 6 Output : [(6, 24, 12), (60, 12, 6)] Explanation : Both tuples have all elements multiple of 6. Input : test_list = [(6, 24, 12), (60, 10, 5), (12, 18, 21)], K = 5 Output : [(60, 10, 5)
7 min read
Python | Detect corner of an image using OpenCV
OpenCV (Open Source Computer Vision) is a computer vision library that contains various functions to perform operations on Images or videos. OpenCV library can be used to perform multiple operations on videos. Let's see how to detect the corner in the image. cv2.goodFeaturesToTrack() method finds N strongest corners in the image by Shi-Tomasi metho
2 min read
PyQt5 – Different border corner of Label
In this article, we will see how to make different types of curves for different corners. We can make borders to a label using setStyleSheet() method but default borders have right angles at the corners i.e not having any curves, but also we can use makes curves by setting border-radius. This will make same curve at all the four corner. Below is th
2 min read
PyQt5 – Different curved Indicator corner in CheckBox
In this article we will see how to set different curves at the different corner of the indicator in check box, although with the help of changing radius we can make square indicator to round indicator. Below is the representation of normal indicator vs the different curved indicator. In order to this, we have to change the style sheet code of indic
2 min read
How to draw a rectangle with rounded corner in PyGame?
Pygame is a Python library designed to develop video games. Pygame adds functionality on top of the excellent SDL library. This allows you to create fully featured games and multimedia programs in the python language. In this article, we will see how can we draw a rectangle with rounded corners in Pygame. Functions Used:pygame.display.set_mode(): T
2 min read
Practice Tags :
three90RightbarBannerImg