Open In App

Construct a square matrix such that the sum of each row and column is odd

Last Updated : 16 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Given an integer N. Then your task is to output a square matrix of length N using the numbers from the range [1, N2] such that the sum of each row and column is odd.

Note: If there are multiple solution, then print any of them.

Examples:

Input: N = 2

Output: {{1, 2}, {4, 3}}

Explanation: Let us calculate the sum of each row and col:

  • First row: R1 is: {1, 2}. Sum is 1+2 = 3, which is odd.
  • Second row: R2 is: {4, 3}. Sum is 4+3 = 7, which is odd.
  • First column: C1 is: {1, 4}. Sum is 1+4 = 5, which is odd.
  • Second column: C2 is: {2, 3}. Sum is 2+3 = 5, which is odd.

The sum of each row and column is odd and all the elements are used in range [1, 4]. Therefore, it’s a valid matrix.

Input: N = 3

Output: {{8, 1, 6}, {3, 5, 7}, {4, 9, 2}}

Explanation: It can be verified that the sum of each row and column is odd and all the elements are used from the range [1, 9].

Approach: Implement the idea below to solve the problem

The problem is observation based. Let us see the main approach to solve the problem. Initially, Initialize the (N*N) matrix by -1. One thing needs to be observed that the sum of any odd numbers, odd times gives odd sum only. Then, we can create the approach for solving the problem for any value of N. Let us see them one by one.

  • If N is Odd: For any odd value of N:
    • 1st row must be full of any N odd numbers.
    • 2nd & 3rd row must contain (N – 2) odd numbers.
    • 4th & 5th row must contain (N – 4) odd numbers and so on…. until your all rows filled up with all odd numbers.
      • For Example: Let us take N = 5, Then we can use the range [1, 25], The matrix will be:
        • 1 3 5 7 9
        • 11 13 15 X X
        • 17 19 21 X X
        • 23 X X X X
        • 25 X X X X
        • The cells containing ‘X’ must be filled with even numbers from the range [1, 25]. Then it can be verified that the sum of all rows and column will be odd.
  • If N is Even: Here we can see a pattern, which is described below. Note that there can many more patterns to do it, It depends upon the imagination and knowledge of individuals.
    • Let us take N = 4, Then we can use numbers from the range [1, 16]. Then, matrix will be:
      • 1 3 5 X
      • X 7 9 11
      • X 13 X X
      • X X 15 X
      • The cells containing ‘X’ must be filled with even numbers from the range [1, 16]. Then it can be verified that the sum of all rows and column will be odd.

Steps taken to solve the problem:

  • Define the function: Start by defining a function Build_matrix() that takes an integer N as an argument.
  • Initialize the matrix: Initialize a N x N matrix with -1. You can do this by creating a 2D array and filling it with -1.
  • Check if N is odd or even: Use an if-else statement to check if N is odd or even.
  • Fill the matrix with odd numbers:
    • If N is odd: fill the first row with odd numbers according to the discussed pattern above and then rest of the rows with odd numbers in a pattern.
    • If N is even: fill the rows with odd numbers in the discussed pattern above.
  • Print the matrix: Finally, print the matrix. You can do this by iterating over the matrix and printing each element.

Code to implement the approach:

C++




// C++ code to implement the approach
#include <iostream>
#include <vector>
using namespace std;
 
// Method to build a square matrix
void Build_matrix(int N) {
    // Initialize a NxN matrix with -1
    vector<vector<int>> ans(N, vector<int>(N, -1));
 
    // If N is odd
    if (N % 2 != 0) {
        int odd = 1;
 
        // Fill the first row with odd numbers
        for (int i = 0; i < N; i++) {
            ans[0][i] = odd;
            odd += 2;
        }
 
        // Fill the rest of the rows with odd numbers in a pattern
        int counter = 1;
        for (int i = 1; i < N; i += 2) {
            for (int j = 0; j < (N - 2 * counter); j++) {
                ans[i][j] = odd;
                odd += 2;
                ans[i + 1][j] = odd;
                odd += 2;
            }
            counter++;
        }
    }
    // If N is even
    else {
        int odd = 1;
 
        // Fill the rows with odd numbers in a pattern
        for (int i = 0; i < N; i += 2) {
            for (int j = i / 2; j < N - 1 - i / 2; j++) {
                ans[i][j] = odd;
                odd += 2;
            }
 
            for (int j = i / 2 + 1; j <= N - 1 - i / 2; j++) {
                ans[i + 1][j] = odd;
                odd += 2;
            }
        }
    }
 
    // Fill the rest of the matrix with even numbers
    int even = 2;
    for (int i = 0; i < N; i++) {
        for (int j = 0; j < N; j++) {
            if (ans[i][j] == -1) {
                ans[i][j] = even;
                even += 2;
            }
        }
    }
 
    // Print the matrix
    for (int i = 0; i < N; i++) {
        for (int j = 0; j < N; j++) {
            cout << ans[i][j] << " ";
        }
        cout << endl;
    }
}
 
// Driver Function
int main() {
    // Input
    int N = 3;
 
    // function call
    Build_matrix(N);
 
    return 0;
}


Java




// Java code to implement the approach
import java.util.*;
 
// Driver Class
class GFG {
 
    // Driver Function
    public static void main(String[] args)
        throws java.lang.Exception
    {
        // Input
        int N = 3;
 
        // function_ call
        Build_matrix(N);
    }
 
    // Method to build a square matrix
    public static void Build_matrix(int N)
    {
        // Initialize a NxN matrix with -1
        int[][] ans = new int[N][N];
        for (int i = 0; i < N; i++) {
            Arrays.fill(ans[i], -1);
        }
 
        // If N is odd
        if (N % 2 != 0) {
            int odd = 1;
 
            // Fill the first row with odd numbers
            for (int i = 0; i < N; i++) {
                ans[0][i] = odd;
                odd += 2;
            }
 
            // Fill the rest of the rows with odd numbers in
            // a pattern
            int counter = 1;
            for (int i = 1; i < N; i += 2) {
                for (int j = 0; j < (N - 2 * counter);
                     j++) {
                    ans[i][j] = odd;
                    odd += 2;
                    ans[i + 1][j] = odd;
                    odd += 2;
                }
                counter++;
            }
        }
        // If N is even
        else {
            int odd = 1;
 
            // Fill the rows with odd numbers in a pattern
            for (int i = 0; i < N; i += 2) {
                for (int j = i / 2; j < N - 1 - i / 2;
                     j++) {
                    ans[i][j] = odd;
                    odd += 2;
                }
 
                for (int j = i / 2 + 1; j <= N - 1 - i / 2;
                     j++) {
                    ans[i + 1][j] = odd;
                    odd += 2;
                }
            }
        }
 
        // Fill the rest of the matrix with even numbers
        int even = 2;
        for (int i = 0; i < N; i++) {
            for (int j = 0; j < N; j++) {
                if (ans[i][j] == -1) {
                    ans[i][j] = even;
                    even += 2;
                }
            }
        }
 
        // Print the matrix
        for (int i = 0; i < N; i++) {
            for (int j = 0; j < N; j++) {
                System.out.print(ans[i][j] + " ");
            }
            System.out.println();
        }
    }
}


Python3




# Method to build a square matrix
def build_matrix(N):
    # Initialize an NxN matrix with -1
    ans = [[-1 for _ in range(N)] for _ in range(N)]
 
    # If N is odd
    if N % 2 != 0:
        odd = 1
 
        # Fill the first row with odd numbers
        for i in range(N):
            ans[0][i] = odd
            odd += 2
 
        # Fill the rest of the rows with odd numbers in a pattern
        counter = 1
        for i in range(1, N, 2):
            for j in range(N - 2 * counter):
                ans[i][j] = odd
                odd += 2
                ans[i + 1][j] = odd
                odd += 2
            counter += 1
    # If N is even
    else:
        odd = 1
 
        # Fill the rows with odd numbers in a pattern
        for i in range(0, N, 2):
            for j in range(i // 2, N - 1 - i // 2):
                ans[i][j] = odd
                odd += 2
 
            for j in range(i // 2 + 1, N - i // 2):
                ans[i + 1][j] = odd
                odd += 2
 
    # Fill the rest of the matrix with even numbers
    even = 2
    for i in range(N):
        for j in range(N):
            if ans[i][j] == -1:
                ans[i][j] = even
                even += 2
 
    # Print the matrix
    for i in range(N):
        for j in range(N):
            print(ans[i][j], end=" ")
        print()
 
 
# Driver Function
if __name__ == "__main__":
    # Input
    N = 3
 
    # Function call
    build_matrix(N)


C#




using System;
 
class Program
{
    // Method to build a square matrix
    static void BuildMatrix(int N)
    {
        // Initialize a NxN matrix with -1
        int[][] ans = new int[N][];
        for (int i = 0; i < N; i++)
        {
            ans[i] = new int[N];
            for (int j = 0; j < N; j++)
            {
                ans[i][j] = -1;
            }
        }
 
        // If N is odd
        if (N % 2 != 0)
        {
            int odd = 1;
 
            // Fill the first row with odd numbers
            for (int i = 0; i < N; i++)
            {
                ans[0][i] = odd;
                odd += 2;
            }
 
            // Fill the rest of the rows with odd numbers in a pattern
            int counter = 1;
            for (int i = 1; i < N; i += 2)
            {
                for (int j = 0; j < (N - 2 * counter); j++)
                {
                    ans[i][j] = odd;
                    odd += 2;
                    ans[i + 1][j] = odd;
                    odd += 2;
                }
                counter++;
            }
        }
        // If N is even
        else
        {
            int odd = 1;
 
            // Fill the rows with odd numbers in a pattern
            for (int i = 0; i < N; i += 2)
            {
                for (int j = i / 2; j < N - 1 - i / 2; j++)
                {
                    ans[i][j] = odd;
                    odd += 2;
                }
 
                for (int j = i / 2 + 1; j <= N - 1 - i / 2; j++)
                {
                    ans[i + 1][j] = odd;
                    odd += 2;
                }
            }
        }
 
        // Fill the rest of the matrix with even numbers
        int even = 2;
        for (int i = 0; i < N; i++)
        {
            for (int j = 0; j < N; j++)
            {
                if (ans[i][j] == -1)
                {
                    ans[i][j] = even;
                    even += 2;
                }
            }
        }
 
        // Print the matrix
        for (int i = 0; i < N; i++)
        {
            for (int j = 0; j < N; j++)
            {
                Console.Write(ans[i][j] + " ");
            }
            Console.WriteLine();
        }
    }
 
    // Driver Function
    static void Main()
    {
        // Input
        int N = 3;
 
        // Function call
        BuildMatrix(N);
    }
}


Javascript




// Method to build a square matrix
function buildMatrix(N) {
    // Initialize a NxN matrix with -1
    let ans = Array.from({ length: N }, () => Array(N).fill(-1));
 
    // If N is odd
    if (N % 2 !== 0) {
        let odd = 1;
 
        // Fill the first row with odd numbers
        for (let i = 0; i < N; i++) {
            ans[0][i] = odd;
            odd += 2;
        }
 
        // Fill the rest of the rows with odd numbers in a pattern
        let counter = 1;
        for (let i = 1; i < N; i += 2) {
            for (let j = 0; j < N - 2 * counter; j++) {
                ans[i][j] = odd;
                odd += 2;
                ans[i + 1][j] = odd;
                odd += 2;
            }
            counter++;
        }
    }
    // If N is even
    else {
        let odd = 1;
 
        // Fill the rows with odd numbers in a pattern
        for (let i = 0; i < N; i += 2) {
            for (let j = i / 2; j < N - 1 - i / 2; j++) {
                ans[i][j] = odd;
                odd += 2;
            }
 
            for (let j = i / 2 + 1; j <= N - 1 - i / 2; j++) {
                ans[i + 1][j] = odd;
                odd += 2;
            }
        }
    }
 
    // Fill the rest of the matrix with even numbers
    let even = 2;
    for (let i = 0; i < N; i++) {
        for (let j = 0; j < N; j++) {
            if (ans[i][j] === -1) {
                ans[i][j] = even;
                even += 2;
            }
        }
    }
 
    // Print the matrix
    for (let i = 0; i < N; i++) {
        console.log(ans[i].join(" "));
    }
}
 
// Driver Function
function main() {
    // Input
    let N = 3;
 
    // Function call
    buildMatrix(N);
}
 
// Execute main function
main();


Output

1 3 5 
7 2 4 
9 6 8 











Time Complexity: O(N2)
Auxiliary Space: O(N2)



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads