Construct a unique matrix n x n for an input n - GeeksforGeeks

21 Apr, 2021
Given an odd integer n, find a matrix of size n x n with following conditions: 
Each cell contains an integer from 1 and n (inclusive).No integer appears twice in the same row or the same column.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.
Each cell contains an integer from 1 and n (inclusive).
No integer appears twice in the same row or the same column.
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++
Java
Python3
C#
Javascript
// 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 rulesvoid 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 codeint 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 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 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 rulesdef 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 coden = 5; # Passing n to constructMatrix functionconstructMatrix(n); # Printing the desired unique matrixfor i in range(n):    for j in range(n):        print(mat[i][j],end=" ");    print("");     # This code is contributed by mits
// 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
<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 rulesfunction 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 Codevar n = 5; // Passing n to constructMatrix functionconstructMatrix(n); // Printing the desired unique matrixfor (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 
nitin mittal
Mithun Kumar
princi singh
Trie
Matrix
Matrix
Trie
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Divide and Conquer | Set 5 (Strassen's Matrix Multiplication)
Program to multiply two matrices
Count all possible paths from top left to bottom right of a mXn matrix
The Celebrity Problem
Min Cost Path | DP-6
Python program to multiply two matrices
Printing all solutions in N-Queen Problem
Multiplication of two Matrices in Single line using Numpy in Python
Real-time application of Data Structures
Search in a row wise and column wise sorted matrix