Open In App

Square submatrices with odd boundary sum

Last Updated : 12 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Given an integer N. The task is to generate a square matrix of (N x N) with the following conditions:

  • The elements of the matrix should be distinct and range from 1 to N*N.
  • The boundary sum of all square sub-matrices starting from A (0, 0) is odd.

In other words, we have to generate a square matrix having unique numbers from 1 to N*N, such that all the square submatrices starting from cell (0, 0) have odd boundary sum.

Note: Print -1 if no such matrix exists.

matrix3x3-(1)

Examples:

Input: 2
Output: -1
Explanation: No such matrix exists following the above criteria.

Input: 3
Output: One possible matrix is:
9 1 7
5 4 8
6 3 2
Explanation: Sum of boundary of submatrix 1 is 9 which is odd.
Sum of boundary of submatrix 2 is 9 + 1 + 5 + 4 = 19 (odd).
Sum of boundary of submatrix 3 is 9 + 1 + 7 + 5 + 8 + 6 + 3 + 2 = 41 (odd).

Approach: To solve the problem, follow the below idea:

The problem can be solved by considering the following cases:

Case 1: N = 2, the matrix is impossible to create because all 1,2,3,4 will be at boundary and their sum can’t be odd

Case 2: N > 3

  • First of all, create a matrix starting from 1 to N^2 row-wise. Like this

1 2 3
4 5 6
7 8 9

  • Now you know that to make boundary sum as odd, you should have odd count of odd numbers of boundary numbers. Initially you will observe that for all submatrices of size>1, the boundary odd count of odd numbers is even. So, you just need to swap one odd boundary number with an even number which is not in boundary.
  • If you swap matrix[2][0] and matrix[2][1] because matrix[2][0] is a boundary odd number and matrix[2][1] is non boundary even number. Then our all submatrices of size > 3 will have odd count of odd numbers.

Case 3: N = 3

  • They still are not unchanged because matrix[2][0] and matrix[2][1] are both boundary numbers for matrix of size 3. Swap matrix[1][1] and matrix[1][2] i.e even and odd element which will affect 3 size matrix and make boundary sum odd.

Below is the implementation of the above approach:

C++
#include <bits/stdc++.h>
using namespace std;

// function to find required matrix
void find_sub_mat(int N)
{
    int matrix[N][N];
    int k = 1;

    // initialisation
    for (int i = 0; i < N; i++) {
        for (int j = 0; j < N; j++) {
            matrix[i][j] = k;
            k++;
        }
    }
    // impossible case
    if (N == 2) {
        cout << -1 << endl;
    }
    else {
        // for submatrices of size 3
        swap(matrix[1][1], matrix[1][2]);
          // this will affect all submatrices of size>3
        swap(matrix[2][0], matrix[2][1]);

        // printing the matrix
        for (int i = 0; i < N; i++) {
            for (int j = 0; j < N; j++) {
                cout << matrix[i][j] << " ";
            }
            cout << endl;
        }
    }
}

int main()
{
    int N = 4;

    // Function call
    find_sub_mat(N);

    return 0;
}
Java
public class Main {
    // function to find required matrix
    static void findSubMatrix(int N) {
        int[][] matrix = new int[N][N];
        int k = 1;

        // initialization
        for (int i = 0; i < N; i++) {
            for (int j = 0; j < N; j++) {
                matrix[i][j] = k;
                k++;
            }
        }

        // impossible case
        if (N == 2) {
            System.out.println(-1);
        } else {
            // for submatrices of size 3
            swap(matrix, 1, 1, 1, 2);
            // this will affect all submatrices of size > 3
            swap(matrix, 2, 0, 2, 1);

            // printing the matrix
            for (int i = 0; i < N; i++) {
                for (int j = 0; j < N; j++) {
                    System.out.print(matrix[i][j] + " ");
                }
                System.out.println();
            }
        }
    }

    // utility function to swap two values
    static void swap(int[][] matrix, int x1, int y1, int x2, int y2) {
        int temp = matrix[x1][y1];
        matrix[x1][y1] = matrix[x2][y2];
        matrix[x2][y2] = temp;
    }

    public static void main(String[] args) {
        int N = 4;

        // Function call
        findSubMatrix(N);
    }
}
C#
using System;

class GFG
{
    // function to find required matrix
    static void FindSubMatrix(int N)
    {
        int[,] matrix = new int[N, N];
        int k = 1;

        // initialization
        for (int i = 0; i < N; i++)
        {
            for (int j = 0; j < N; j++)
            {
                matrix[i, j] = k;
                k++;
            }
        }

        // impossible case
        if (N == 2)
        {
            Console.WriteLine(-1);
        }
        else
        {
            // for submatrices of size 3
            Swap(ref matrix[1, 1], ref matrix[1, 2]);
            // this will affect all submatrices of size > 3
            Swap(ref matrix[2, 0], ref matrix[2, 1]);

            // printing the matrix
            for (int i = 0; i < N; i++)
            {
                for (int j = 0; j < N; j++)
                {
                    Console.Write(matrix[i, j] + " ");
                }
                Console.WriteLine();
            }
        }
    }

    // utility function to swap two values
    static void Swap(ref int a, ref int b)
    {
        int temp = a;
        a = b;
        b = temp;
    }

    static void Main()
    {
        int N = 4;

        // Function call
        FindSubMatrix(N);
    }
}
Javascript
function findSubMatrix(N) {
    let matrix = [];
    let k = 1;

    // initialization
    for (let i = 0; i < N; i++) {
        matrix.push([]);
        for (let j = 0; j < N; j++) {
            matrix[i][j] = k;
            k++;
        }
    }

    // impossible case
    if (N === 2) {
        console.log(-1);
    } else {
        // for submatrices of size 3
        [matrix[1][1], matrix[1][2]] = [matrix[1][2], matrix[1][1]];
        // this will affect all submatrices of size > 3
        [matrix[2][0], matrix[2][1]] = [matrix[2][1], matrix[2][0]];

        // printing the matrix
        for (let i = 0; i < N; i++) {
            console.log(matrix[i].join(" "));
        }
    }
}

// Sample Input
let N = 4;

// Function call
findSubMatrix(N);

// This code is contributed by shivamgupta0987654321
Python3
def find_sub_mat(N):
    matrix = [[0 for _ in range(N)] for _ in range(N)]
    k = 1

    # Initialization
    for i in range(N):
        for j in range(N):
            matrix[i][j] = k
            k += 1

    # Impossible case
    if N == 2:
        print(-1)
    else:
        # For submatrices of size 3
        matrix[1][1], matrix[1][2] = matrix[1][2], matrix[1][1]
        # This will affect all submatrices of size > 3
        matrix[2][0], matrix[2][1] = matrix[2][1], matrix[2][0]

        # Printing the matrix
        for i in range(N):
            for j in range(N):
                print(matrix[i][j], end=" ")
            print()

# Main function
def main():
    N = 4

    # Function call
    find_sub_mat(N)

if __name__ == "__main__":
    main()

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








Time Complexity: O(N*N), where N is the number of rows or columns in the matrix.
Auxiliary space: O(N*N)



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads