Skip to content
Related Articles

Related Articles

Improve Article
Construct a unique matrix n x n for an input n
  • Difficulty Level : Hard
  • Last Updated : 21 Apr, 2021

Given an odd integer n, find a matrix of size n x n with following conditions:
 

  1. Each cell contains an integer from 1 and n (inclusive).
  2. No integer appears twice in the same row or the same column.
  3. All 1’s must be at every possible distance from the center of the matrix. The center of a n x n square is cell ((n-1)/2, (n-1)/2) for odd n.

Example : 
 

Input  : n = 1
Output : 1

Input : n = 3
Output: 3 2 1
        1 3 2
        2 1 3

Input : n = 5
Output : 5 3 2 4 1 
         1 4 3 5 2 
         2 5 4 1 3 
         3 1 5 2 4 
         4 2 1 3 5 
 

 

The idea is to first decide positions of 1s. Once possible arrangement of 1s for n = 5 is, 
 

_ _ _ _ 1 
1 _ _ _ _ 
_ _ _ 1 _ 
_ 1 _ _ _ 
_ _ 1 _ _ 

Once we have decided 1s, task of filling remaining items is simple. We fill remaining entries column by column. For every 1, we traverse its column and fill all entries below it with 2, 3,…p and fill all entries above it with p+1, .. n. We get following.
 



5 3 2 4 1 
1 4 3 5 2 
2 5 4 1 3 
3 1 5 2 4 
4 2 1 3 5 

To decide initial positions of 1s, we traverse all rows and keep track of two column numbers “left” and “right”. 
1) “right” starts with n-1 and keep decrementing after every alternate row. 
2) “left” starts with 0 and keep incrementing after every alternate row. 
Below are implementations of above idea. 
 

C++




// C++ program to construct an n x n
// matrix such that every row and every
// column has distinct values.
#include <iostream>
#include <bits/stdc++.h>
 
using namespace std;
 
const int MAX = 100;
int mat[MAX][MAX];
 
// Fills non-one entries in column j
// Given that there is a "1" at
// position mat[i][j], this function
// fills other entries of column j.
void fillRemaining(int i, int j, int n)
{
    // Initialize value to be filled
    int x = 2;
 
    // Fill all values below i as 2, 3, ...p
    for (int k = i + 1; k < n; k++)
        mat[k][j] = x++;
 
    // Fill all values above i
    // as p + 1, p + 2, .. n
    for (int k = 0; k < i; k++)
        mat[k][j] = x++;
}
 
// Fills entries in mat[][]
// with the given set of rules
void constructMatrix(int n)
{
    // Alternatively fill 1s starting from
    // rightmost and leftmost columns. For
    // example for n = 3, we get { {_ _ 1},
    // {1 _ _} {_ 1 _}}
    int right = n - 1, left = 0;
    for (int i = 0; i < n; i++)
    {
        // If i is even, then fill 
        // next column from right
        if (i % 2 == 0)
        {
            mat[i][right] = 1;
 
            // After filling 1, fill remaining
            // entries of column "right"
            fillRemaining(i, right, n);
 
            // Move right one column back
            right--;
        }
         
        // Fill next column from left
        else
        {
            mat[i][left] = 1;
 
            // After filling 1, fill remaining
            // entries of column "left"
            fillRemaining(i, left, n);
 
            // Move left one column forward
            left++;
        }
    }
}
 
// Driver code
int main()
{
    int n = 5;
 
    // Passing n to constructMatrix function
    constructMatrix(n);
 
    // Printing the desired unique matrix
    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < n; j++)
            printf("%d ",mat[i][j]);
        printf ("\n");
    }
    return 0;
}

Java




// Java program to construct an n x n
// matrix such that every row and every
// column has distinct values.
class GFG
{
     
    static final int MAX = 100;
    static int[][] mat = new int[MAX][MAX];
     
    // Fills non-one entries in column j
    // Given that there is a "1" at
    // position mat[i][j], this function
    // fills other entries of column j.
    static void fillRemaining(int i, int j, int n)
    {
        // Initialize value to be filled
        int x = 2;
     
        // Fill all values below i as 2, 3, ...p
        for (int k = i + 1; k < n; k++)
            mat[k][j] = x++;
     
        // Fill all values above i
        // as p + 1, p + 2, .. n
        for (int k = 0; k < i; k++)
            mat[k][j] = x++;
    }
     
    // Fills entries in mat[][]
    // with the given set of rules
    static void constructMatrix(int n)
    {
        // Alternatively fill 1s starting from
        // rightmost and leftmost columns. For
        // example for n = 3, we get { {_ _ 1},
        // {1 _ _} {_ 1 _}}
        int right = n - 1, left = 0;
        for (int i = 0; i < n; i++)
        {
            // If i is even, then fill
            //  next column from right
            if (i % 2 == 0)
            {
                mat[i][right] = 1;
     
                // After filling 1, fill remaining
                // entries of column "right"
                fillRemaining(i, right, n);
     
                // Move right one column back
                right--;
            }
             
            // Fill next column from left
            else
            {
                mat[i][left] = 1;
     
                // After filling 1, fill remaining
                // entries of column "left"
                fillRemaining(i, left, n);
     
                // Move left one column forward
                left++;
            }
        }
    }
     
    // Driver Code
    public static void main(String args[])
    {
        int n = 5;
     
        // Passing n to constructMatrix function
        constructMatrix(n);
     
        // Printing the desired unique matrix
        for (int i = 0; i < n; i++)
        {
            for (int j = 0 ; j < n; j++)
            System.out.print(mat[i][j]+" ");
            System.out.println();
        }
    }
}
 
// This code is contributed by Sumit Ghosh

Python3




# Python3 program to construct an n x n
# matrix such that every row and every
# column has distinct values.
 
MAX = 100;
mat = [[0 for x in range(MAX)] for y in range(MAX)];
 
# Fills non-one entries in column j
# Given that there is a "1" at
# position mat[i][j], this function
# fills other entries of column j.
def fillRemaining(i, j, n):
 
    # Initialize value to be filled
    x = 2;
 
    # Fill all values below i as 2, 3, ...p
    for k in range(i + 1,n):
        mat[k][j] = x;
        x+=1;
 
    # Fill all values above i
    # as p + 1, p + 2, .. n
    for k in range(i):
        mat[k][j] = x;
        x+=1;
 
# Fills entries in mat[][]
# with the given set of rules
def constructMatrix(n):
 
    # Alternatively fill 1s starting from
    # rightmost and leftmost columns. For
    # example for n = 3, we get { {_ _ 1},
    # {1 _ _} {_ 1 _}}
    right = n - 1;
    left = 0;
    for i in range(n):
        # If i is even, then fill
        # next column from right
        if (i % 2 == 0):
            mat[i][right] = 1;
 
            # After filling 1, fill remaining
            # entries of column "right"
            fillRemaining(i, right, n);
 
            # Move right one column back
            right-=1;
         
        # Fill next column from left
        else:
            mat[i][left] = 1;
 
            # After filling 1, fill remaining
            # entries of column "left"
            fillRemaining(i, left, n);
 
            # Move left one column forward
            left+=1;
 
# Driver code
n = 5;
 
# Passing n to constructMatrix function
constructMatrix(n);
 
# Printing the desired unique matrix
for i in range(n):
    for j in range(n):
        print(mat[i][j],end=" ");
    print("");
     
# This code is contributed by mits

C#




// C# program to construct an n x n
// matrix such that every row and
// every column has distinct values.
using System;
 
class GFG
{
     
    static int MAX = 100;
    static int [,]mat = new int[MAX, MAX];
     
    // Fills non-one entries in column j
    // Given that there is a "1" at
    // position mat[i][j], this function
    // fills other entries of column j.
    static void fillRemaining(int i, int j, int n)
    {
        // Initialize value to be filled
        int x = 2;
     
        // Fill all values below i as 2, 3, ...p
        for (int k = i + 1; k < n; k++)
            mat[k, j] = x++;
     
        // Fill all values above i
        // as p + 1, p + 2, .. n
        for (int k = 0; k < i; k++)
            mat[k, j] = x++;
    }
     
    // Fills entries in mat[][]
    // with the given set of rules
    static void constructMatrix(int n)
    {
        // Alternatively fill 1s starting from
        // rightmost and leftmost columns. For
        // example for n = 3, we get { {_ _ 1},
        // {1 _ _} {_ 1 _}}
        int right = n - 1, left = 0;
        for (int i = 0; i < n; i++)
        {
            // If i is even, then fill
            // next column from right
            if (i % 2 == 0)
            {
                mat[i, right] = 1;
     
                // After filling 1, fill remaining
                // entries of column "right"
                fillRemaining(i, right, n);
     
                // Move right one column back
                right--;
            }
             
            // Fill next column from left
            else
            {
                mat[i, left] = 1;
     
                // After filling 1, fill remaining
                // entries of column "left"
                fillRemaining(i, left, n);
     
                // Move left one column forward
                left++;
            }
        }
    }
     
    // Driver Code
    public static void Main()
    {
        int n = 5;
     
        // Passing n to constructMatrix function
        constructMatrix(n);
     
        // Printing the desired unique matrix
        for (int i = 0; i < n; i++)
        {
            for (int j = 0 ; j < n; j++)
            Console.Write(mat[i, j]+" ");
            Console.WriteLine();
        }
    }
}
 
// This code is contributed by nitin mittal

Javascript




<script>
 
// javascript program to construct an n x n
// matrix such that every row and every
// column has distinct values.
 
     
var MAX = 100;
var mat = Array(MAX).fill(0).
          map(x => Array(MAX).fill(0));
 
// Fills non-one entries in column j
// Given that there is a "1" at
// position mat[i][j], this function
// fills other entries of column j.
function fillRemaining(i , j , n)
{
    // Initialize value to be filled
    var x = 2;
 
    // Fill all values below i as 2, 3, ...p
    for (k = i + 1; k < n; k++)
        mat[k][j] = x++;
 
    // Fill all values above i
    // as p + 1, p + 2, .. n
    for (k = 0; k < i; k++)
        mat[k][j] = x++;
}
 
// Fills entries in mat
// with the given set of rules
function constructMatrix(n)
{
    // Alternatively fill 1s starting from
    // rightmost and leftmost columns. For
    // example for n = 3, we get { {_ _ 1],
    // {1 _ _} {_ 1 _}}
    var right = n - 1, left = 0;
    for (i = 0; i < n; i++)
    {
        // If i is even, then fill
        //  next column from right
        if (i % 2 == 0)
        {
            mat[i][right] = 1;
 
            // After filling 1, fill remaining
            // entries of column "right"
            fillRemaining(i, right, n);
 
            // Move right one column back
            right--;
        }
         
        // Fill next column from left
        else
        {
            mat[i][left] = 1;
 
            // After filling 1, fill remaining
            // entries of column "left"
            fillRemaining(i, left, n);
 
            // Move left one column forward
            left++;
        }
    }
}
 
// Driver Code
var n = 5;
 
// Passing n to constructMatrix function
constructMatrix(n);
 
// Printing the desired unique matrix
for (i = 0; i < n; i++)
{
    for (j = 0 ; j < n; j++)
    document.write(mat[i][j]+" ");
    document.write('<br>');
}
 
// This code contributed by Princi Singh
 
</script>

Output : 

5 3 2 4 1 
1 4 3 5 2 
2 5 4 1 3 
3 1 5 2 4 
4 2 1 3 5 

This article is contributed by MAZHAR IMAM KHAN. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
 

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with industry experts, please refer DSA Live Classes 




My Personal Notes arrow_drop_up
Recommended Articles
Page :